import zipfile
import sys
import os
import io
from datetime import datetime
from flask import Blueprint, render_template, redirect, request, Response, send_file, send_from_directory, jsonify
import re
from .apis import Apis
import json
import time
import io
# import numpy as np
# import csv
# import pandas as pd
# import yaml
import struct
import math
import ctypes
import random

# import matplotlib
# # import matplotlib.pyplot as plt
# matplotlib.use('Agg')
# from matplotlib import pyplot as plt

# from matplotlib.pyplot import *

# from collections import namedtuple
# import abc
# from scipy import interpolate

# from math import cos, sin, pi

# from collections import defaultdict

# NB_BIT_PER_RF_REG = 32

# from .broker import Broker

# from .dspCoreVol import DspCoreVol
# from .cdb import CDB
# from .dpin import DPin
# from .ain import Ain
# from .aout import Aout
# from .cosa import COSA

# from .canopus import Canopus
# from .canopus_api import CanopusApi
# from .deneb_api import DenebApi

# from .laser import Laser
# from .abc import ABC
# from .ddm import DDM
# from .cmis import CMIS
# from . import crc
# from openpyxl import load_workbook, Workbook


#from crc import Crc32
# from .flash import Flash

# from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
# from matplotlib.figure import Figure

# import matplotlib
# import matplotlib.pyplot as plt

# here define a route
module_bp = Blueprint(
    'module',
    '__name__',
)

a = Apis()
for_customer = a.is_for_customer()

# @module_bp.route('/mod_cosa')
# def mod_cosa():
#     return render_template('mod_cosa.html', title='COSA',for_customer=for_customer)


# @module_bp.route('/mod_host')
# def mod_host():
#     return render_template('module.html', title='MSA',for_customer=for_customer)


# @module_bp.route('/api/get_twi_rate')
# def get_twi_rate():
#     return a.get_twi_rate()


# @module_bp.route('/api/set_twi_rate', methods=['POST'])
# def set_twi_rate():
#     twi_rate = request.form["twi_rate"]
#     a.set_twi_rate(twi_rate)
#     return "set_twi_rate ok"


# @module_bp.route('/api/get_twi_if')
# def get_twi_if():
#     return a.din_get(5)


# @module_bp.route('/api/get_module_state')
# def get_module_state():
#     module_state_map = {
#         '000': 'Reserved',
#         '001': 'LowPwr',
#         '010': 'PwrUp',
#         '011': 'Ready',
#         '100': 'PwrDn',
#         '101': 'Fault',
#         '110': 'Reserved',
#         '111': 'Reserved'
#     }
#     ret = a.get_twi(1, 0x3)
#     ret1 = ret.split(',')[0]  #hex
#     ret2 = int(ret1, 16)

#     idx = '{:08b}'.format(ret2)[4:7]
#     return idx + ',' + module_state_map[idx]


# @module_bp.route('/api/get_dp_state')
# def get_dp_state():
#     dp_state_map = {
#         1: 'DataPathDeactivated State',
#         2: 'DataPathInit State',
#         3: 'DataPathDeinit State',
#         4: 'DataPathActivated State',
#         5: 'DataPathTxTurnOn State',
#         6: 'DataPathTxTurnOff State',
#         7: 'DataPathInitialized State'
#     }

#     b = Broker()
#     c = CMIS(b)
#     dp_state = c.dp_state
#     # print(dp_state)
#     # print(type(dp_state))
#     if dp_state < 1 or dp_state > 7:
#         return 'Reserved'
#     else:
#         return str(dp_state) + ", " + dp_state_map[dp_state]


# @module_bp.route('/api/analog2_evt_set', methods=['POST'])
# def analog2_evt_set():
#     analog2_phy_val = request.form["analog2_phy_val"]
#     # item_val = analog2[item]
#     item_val = 101
#     # turn on P3V3_OSFP_IN_EN LED
#     a.dout_set(29, 1)
#     time.sleep(0.1)
#     a.aout_set(int(item_val), float(analog2_phy_val))
#     return "set_analog2 ok"


# @module_bp.route('/api/analog2_evt_get', methods=['POST'])
# def analog2_evt_get():
#     # item = request.form["item"]
#     # item_val = analog2[item]
#     item_val = 101
#     cells_val = a.aout_get(int(item_val))
#     return cells_val


# @module_bp.route('/api/get_pin_state', methods=['POST'])
# def get_pin_state():
#     idx = int(request.form["idx"])
#     if idx < 10:
#         state = a.din_get(idx)
#     else:
#         state = a.dout_get(idx)
#     return state


# @module_bp.route('/api/set_pin_state', methods=['POST'])
# def set_pin_state():
#     idx = int(request.form["idx"])
#     pin_idx_val = int(request.form["pin_idx_val"])
#     a.dout_set(idx, pin_idx_val)
#     print("set_gpio_gpio_1... ok")
#     return "set_gpio_gpio_1... ok"


# @module_bp.route('/api/get_module_power', methods=['POST'])
# def get_module_power():
#     # "P3V3_OSFP_IN_EN", 27
#     state = a.dout_get(27)
#     return state


# @module_bp.route('/api/set_module_power', methods=['POST'])
# def set_module_power():
#     idx = int(request.form["idx"])
#     val = int(request.form["val"])
#     a.dout_set(idx, val)
#     print("set_module_power... ok")
#     return "set_module_power... ok"



# @module_bp.route('/api/get_cmis_revision', methods=['POST'])
# def get_cmis_revision():
#     #get current cmis revision
#     ret = a.get_twi(1, 1)
#     ret1 = ret.split(',')[0]
#     print(ret1)
#     return ret1


# @module_bp.route('/api/set_cmis_revision', methods=['POST'])
# def set_cmis_revision():
#     b = Broker()
#     cmis_revision = str(request.form["cmis_revision"])
#     print(cmis_revision)
#     # 1. SW reset(lower page26 = 0x08), 
#     a.set_twi(1, 26, 0x08)

#     # 2. LP mode pin assert(b.MOD_LPWn=True), 
#     b.MOD_LPWn = 1
#     time.sleep(2)

#     # 3. PW entry(b.cdb_psw()), 
#     b.cdb_psw()

#     # 4. Write new CMIS Rev value to LowMem: Register 1, 
#     a.set_twi(1, 1, int('0x'+cmis_revision, 16))

#     # 5. POR command(pageb0h:255 = 1), 
#     a.set_twi(1, 127, 0xb0)
#     a.set_twi(1, 255, 0x1)

#     # 6. 2 sec wait, 
#     time.sleep(2)

#     # 7. SW reset(lower page26 = 0x08), 
#     a.set_twi(1, 26, 0x08)

#     # 8 .deassert LP pin(b.MOD_LPWn=False),
#     b.MOD_LPWn = 0

#     print("set_cmis_revision... ok")
#     return "set_cmis_revision... ok"



# @module_bp.route('/api/btn_set_ddb_password', methods=['POST'])
# def btn_set_ddb_password():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     return "Set DDB password OK."


# @module_bp.route('/api/btn_fan_set', methods=['POST'])
# def btn_fan_set():
#     fan = request.form["fan"]
#     print("/api/btn_fan_set")
#     print('*fan ' + str(fan))
#     a.comm_cmdstr_setter('*FAN ' + str(fan))
#     return "btn_fan_set... ok"


# ##################################################
# # MSA PAGE
# ##################################################
# @module_bp.route('/api/get_msa_values')
# def get_msa_values():
#     msa_values = {}
#     # btn_get_twi_rate
#     msa_values.update({"twi_rate": a.get_twi_rate()})
#     # btn_get_twi_if
#     msa_values.update({"twi_if": a.din_get(5)})
#     # btn_analog2_evt_get
#     msa_values.update({"p3v3": a.aout_get(101)})
#     # btn_get_pin_state(20);
#     msa_values.update({"txt_pin_idx_20": a.dout_get(20)})
#     # btn_get_pin_state(21);
#     msa_values.update({"txt_pin_idx_21": a.dout_get(21)})
#     # btn_get_pin_state(1);
#     msa_values.update({"txt_pin_idx_1": a.din_get(1)})
#     # btn_get_pin_state(2);
#     msa_values.update({"txt_pin_idx_2": a.din_get(2)})
#     return json.dumps(msa_values)


# ##################################################
# # LOW/UP PAGE
# ##################################################
# @module_bp.route('/api/get_vdm_all')
# def get_vdm_all():
#     print("--------get_vdm_all----------")
#     b = Broker()
#     c = CMIS(b)
#     print(str(c.vdm_all))

#     idx = 1;
#     vdm_all_info = "<table class='table'>"
#     for k, v in c.vdm_all.items():
        
#         if idx%2 == 0:
#             vdm_all_info += "<tr>" + vdm_all_item + "<td width='20%'>{}</td> <td class='display_resp' width='30%'>{}</td></tr>".format(k, v)
#         else:
#             vdm_all_item = ""
#             vdm_all_item =  "<td width='20%'>{}</td> <td class='display_resp' width='30%'>{}</td>".format(k, v)
#         idx = idx + 1

#     vdm_all_info += "</table>"
#     return vdm_all_info
#     # return "vdm all info here ..."


# @module_bp.route('/api/get_vdm_decode')
# def get_vdm_decode():
#     print("--------get_vdm_decode----------")
#     b = Broker()
#     c = CMIS(b)
#     print(str(c.vdm_decode))

#     idx = 1;
#     vdm_all_info = "<table class='table'>"
#     for k, v in c.vdm_decode.items():
        
#         if idx%2 == 0:
#             vdm_all_info += "<tr>" + vdm_all_item + "<td width='25%'>{}</td> <td class='display_resp' width='25%'>{}</td></tr>".format(k.upper() if ' ' not in k else k.title(), v)
#         else:
#             vdm_all_item = ""
#             vdm_all_item =  "<td width='25%'>{}</td> <td class='display_resp' width='25%'>{}</td>".format(k.upper() if ' ' not in k else k.title(), v)
#         idx = idx + 1

#     vdm_all_info += "</table>"
#     return vdm_all_info
#     # return "vdm all info here ..."




# if for_customer == 'hide':
#     pages = [{
#         'Lower Page': '---',
#         'Page 00h': 'Administrative Information (Read-only)',
#         'Page 01h': 'Advertising',
#         'Page 02h': 'Module and Lane Thresholds',
#         'Page 03h': '---',
#         'Page 04h': 'Module and Lane Thresholds'
#     }, {
#         'Page 10h': 'Lane and Data Path Control',
#         'Page 11h': 'Lane Status',
#         'Page 12h': 'Tuneable Laser Control and Status',
#         'Page 13h': 'Module Diagnostics 1',
#         'Page 14h': 'Module Diagnostics 2',
#         'Page 20h': 'Config for Parameter 1-64 (Group 1)'
#     }, {
#         'Page 21h': 'Config for Parameter 65-128 (Group 2)',
#         'Page 22h': 'Config for Parameter 129-192 (Group 3)',
#         'Page 23h': 'Config for Parameter 193-256 (Group 4)',
#         'Page 24h': 'Real Time Values Parameter 1-64 (Group 1)',
#         'Page 25h': 'Real Time Values Parameter 65-128 (Group 2)',
#         'Page 26h': 'Real Time Values Parameter 129-192 (Group 3)'
#     }, {
#         'Page 27h': 'Real Time Values Parameter 193-256 (Group 4)',
#         'Page 28h': 'Threshold for Parameter 0-15 (Group 1)',
#         'Page 29h': 'Threshold for Parameter 16-31 (Group 2)',
#         'Page 2Ah': 'Threshold for Parameter 32-47 (Group 3)',
#         'Page 2Bh': 'Threshold for Parameter 48-63 (Group 4)',
#         'Page 2Ch': 'Alarms (all groups)'
#     }, {
#         'Page 2Dh': 'Masks (all groups)',
#         'Page 2Eh': 'Reserved',
#         'Page 2Fh': 'Controls',
#         'Page 30h': 'Media Lane Configurable Thresholds',
#         'Page 31h': 'Media Lane Provisioning',
#         'Page 32h': 'Media Lane Flag Masks'
#     }, {
#         'Page 33h': 'Media Lane Flags and Status',
#         'Page 34h': 'Lane FEC Performance Monitoring',
#         'Page 35h': 'Media Lane Link Performance Monitoring',
#         'Page 38h': 'Data Path Host Interface Configuration',
#         'Page 3Ah': 'Data Path Host Interface Performance Monitoring',
#         'Page 3Bh': 'Data Path Host Interface Flags and Masks'
#     }, {
#         'Page 41h': 'Rx Signal Power Advertisement and Ranges for Configurable Thresholds',
#         'Page 42h': 'Performance Monitoring Advertisement',
#         'Page 43h': 'Media Lane Provisioning Advertisement',
#         'Page 9Fh': '---',
#         'Page A0h': '---',
#         'Page A1h': '---'
#     }, {
#         'Page A2h': '---',
#         'Page A3h': '---',
#         'Page A4h': '---',
#         'Page A5h': '---',
#         'Page A6h': '---',
#         'Page A7h': '---'
#     }, {
#         'Page A8h': '---',
#         'Page A9h': '---',
#         'Page AAh': '---',
#         'Page ABh': '---',
#         'Page ACh': '---',
#         'Page ADh': '---'
#     }, {
#         'Page AEh': '---',
#         'Page AFh': '---'
#     }]
# else:
#     pages = [{
#         'Lower Page': '---',
#         'Page 00h': 'Administrative Information (Read-only)',
#         'Page 01h': 'Advertising',
#         'Page 02h': 'Module and Lane Thresholds',
#         'Page 03h': '---',
#         'Page 04h': 'Module and Lane Thresholds'
#     }, {
#         'Page 10h': 'Lane and Data Path Control',
#         'Page 11h': 'Lane Status',
#         'Page 12h': 'Tuneable Laser Control and Status',
#         'Page 13h': 'Module Diagnostics 1',
#         'Page 14h': 'Module Diagnostics 2',
#         'Page 20h': 'Config for Parameter 1-64 (Group 1)'
#     }, {
#         'Page 21h': 'Config for Parameter 65-128 (Group 2)',
#         'Page 22h': 'Config for Parameter 129-192 (Group 3)',
#         'Page 23h': 'Config for Parameter 193-256 (Group 4)',
#         'Page 24h': 'Real Time Values Parameter 1-64 (Group 1)',
#         'Page 25h': 'Real Time Values Parameter 65-128 (Group 2)',
#         'Page 26h': 'Real Time Values Parameter 129-192 (Group 3)'
#     }, {
#         'Page 27h': 'Real Time Values Parameter 193-256 (Group 4)',
#         'Page 28h': 'Threshold for Parameter 0-15 (Group 1)',
#         'Page 29h': 'Threshold for Parameter 16-31 (Group 2)',
#         'Page 2Ah': 'Threshold for Parameter 32-47 (Group 3)',
#         'Page 2Bh': 'Threshold for Parameter 48-63 (Group 4)',
#         'Page 2Ch': 'Alarms (all groups)'
#     }, {
#         'Page 2Dh': 'Masks (all groups)',
#         'Page 2Eh': 'Reserved',
#         'Page 2Fh': 'Controls',
#         'Page 30h': 'Media Lane Configurable Thresholds',
#         'Page 31h': 'Media Lane Provisioning',
#         'Page 32h': 'Media Lane Flag Masks'
#     }, {
#         'Page 33h': 'Media Lane Flags and Status',
#         'Page 34h': 'Lane FEC Performance Monitoring',
#         'Page 35h': 'Media Lane Link Performance Monitoring',
#         'Page 38h': 'Data Path Host Interface Configuration',
#         'Page 3Ah': 'Data Path Host Interface Performance Monitoring',
#         'Page 3Bh': 'Data Path Host Interface Flags and Masks'
#     }, {
#         'Page 41h': 'Rx Signal Power Advertisement and Ranges for Configurable Thresholds',
#         'Page 42h': 'Performance Monitoring Advertisement',
#         'Page 43h': 'Media Lane Provisioning Advertisement',
#         'Page 9Fh': '---',
#         'Page A0h': '---',
#         'Page A1h': '---'
#     }, {
#         'Page A2h': '---',
#         'Page A3h': '---',
#         'Page A4h': '---',
#         'Page A5h': '---',
#         'Page A6h': '---',
#         'Page A7h': '---'
#     }, {
#         'Page A8h': '---',
#         'Page A9h': '---',
#         'Page AAh': '---',
#         'Page ABh': '---',
#         'Page ACh': '---',
#         'Page ADh': '---'
#     }, {
#         'Page AEh': '---',
#         'Page AFh': '---',
#         'Page FFh': '---'
#     }]


# # rebranding mode （page00h: 221 is NOT 0）， the following register R+W：
# # •   00h:129-199, 223-255
# # •   Lower page register 1
# def select_templates_filename():
#     # a.set_twi(1, 127, 0x00)
#     try:
#         ret = a.get_twi(1, 221)
#         ret1 = ret.split(',')[0]  
#         print('--------------------------')
#         print(int(ret.split(',')[0], 16))
#         print('--------------------------')
#         if int(ret.split(',')[0], 16) == 0:
#             return './templates/files/OSFP_GUI_CMIS_MMR.xlsm'
#         else:
#             return './templates/files/OSFP_GUI_CMIS_MMR_rebranding.xlsm'
#     except:
#         return './templates/files/OSFP_GUI_CMIS_MMR.xlsm'


# @module_bp.route('/page_template')
# def page_template():
#     try:
#         set_password()
#     except:
#         pass
#     page_name = request.args.get('page_name')
#     print('-----------------')
#     print(page_name)
#     # Page 00h
#     print('-----------------')
#     # SET UP PAGE--------------------------------------------------------
#     if page_name == "Lower Page":
#         pass
#     elif 'Page_Blank' in page_name:
#         page_select_byte = '0x' + page_name.split('_')[2][0:2]
#         page_name = 'Page Blank'
#         a.set_twi(1, 127, page_select_byte)
#     else:
#         try:
#             page_select_byte = '0x' + page_name.split(' ')[1][0:2]
#             a.set_twi(1, 127, page_select_byte)
#             # def set_twi(self, len, address, data=None):
#         except:
#             pass

#     page_title = ''
#     for item in pages:
#         if page_name in item.keys():
#             if item[page_name] == '---':
#                 page_title = ''
#             else:
#                 page_title = item[page_name]
#             break

#     templates_filename = select_templates_filename()
#     print('current use templates_filename: ', templates_filename)

#     data = pd.read_excel(templates_filename,
#                          sheet_name=page_name,
#                          usecols=[0, 1, 2, 3, 4, 5],
#                          skiprows=[0])
#     # print(type(data))
#     big_list = []


#     try:
#         for index, row in data.iterrows():
#             row_list = []
#             lst_all = []
#             for i in range(len(row)):
#                 # print(row[i])
#                 row_list.append(str(row[i]).replace('\n', '<BR>'))

#             ret = a.get_twi(1, row[0])
#             ret1 = ret.split(',')[0]  #hex
#             row_list.append(int(ret1, 16))
#             row_list.append(ret1.upper())
#             row_list.append('{:08b}'.format(int(ret1, 16)))

#             if int(ret1, 16) > 32 and int(ret1, 16) < 127:
#                 row_list.append(chr(int(ret1, 16)))
#             else:
#                 row_list.append('')

#             big_list.append(row_list)
#         # print(big_list)
#         # Get Current Vals---------------------------------------------------
#         lst_all = []
#         for address in range(0, 128):
#             ret = a.get_twi(1, address)
#             ret1 = ret.split(',')[0]  #hex
#             lst = []
#             lst.append(int(ret1, 16))  #dec
#             lst.append(ret1.upper())
#             lst.append('{:08b}'.format(int(ret1, 16)))  #bin
#             lst_all.append(lst)
#             # print(lst_all)
#     except:  #if except return demo data to GUI
#         for index, row in data.iterrows():
#             row_list = []
#             lst_all = []
#             for i in range(len(row)):
#                 # print(row[i])
#                 row_list.append(str(row[i]).replace('\n', '<BR>'))

#             # row_list.append('0')
#             # row_list.append('0x0')
#             # row_list.append('{:08b}'.format(0))
#             # Chrï¼? N
#             row_list.append('78')
#             row_list.append('0x4E')
#             row_list.append('01001110')
#             # row_list.append('N')
#             demo_chr = 78
#             if demo_chr > 32 and demo_chr < 127:
#                 row_list.append(chr(demo_chr))
#             else:
#                 row_list.append('')

#             big_list.append(row_list)
#         # print(big_list)
#         # Get Current Vals---------------------------------------------------
#         lst_all = []
#         for address in range(0, 128):
#             lst = []
#             lst.append('0')  #dec
#             lst.append('0x0')
#             lst.append('{:08b}'.format(0))  #bin
#             lst_all.append(lst)

#     lst_all_data = json.dumps(lst_all)
#     # print("-----------------------------------------------------------")
#     # print(lst_all_data)
#     # print("-----------------------------------------------------------")

#     if 'Page_Blank' in request.args.get('page_name'):
#         page_name = "Page_Blank_" + str(request.args.get('page_name').split('_')[2][0:2]).upper()
#         # page_name = "Page_Blank_" + str(request.args.get('page_name').split('_')[2][0:2]).upper() + 'h'

#     return render_template('page_template.html',
#                            title='Pages View',
#                            big_list=big_list,
#                            page_name=page_name,
#                            pages=pages,
#                            lst_all_data=lst_all_data,
#                            page_title=page_title,
#                            for_customer=for_customer)


# @module_bp.route('/set_page_val', methods=['POST'])
# def set_page_val():
#     reg_address = request.form["reg_address"]
#     reg_val_hex = request.form["reg_val_hex"]
#     try:
#         a.set_twi(1, reg_address, reg_val_hex)
#     except:
#         pass

#     return "set_page_val ok"


# @module_bp.route('/jump_to_page', methods=['POST'])
# def jump_to_page():
#     return "jump_to_page ok"

# ##################################################
# # TEST PAGE
# ##################################################
# @module_bp.route('/test')
# def test():
#     return render_template('test.html', title='Test Page',for_customer=for_customer)


# @module_bp.route('/btn_scan_freq', methods=['GET', 'POST'])
# def btn_scan_freq():
#     print("btn_scan_freq ...")
#     # path = './static/files/test.csv'
#     ch = request.form["ch"]
#     print("params ....")
#     print(ch)
#     ret = os.system("python scan_freq.py")
#     if ret == 0:
#         return "QDD-Scan-Freq-Test-log.csv"
#     else:
#         return "error"


# @module_bp.route('/btn_fixed_freq', methods=['GET', 'POST'])
# def btn_fixed_freq():
#     print("btn_scan_freq ...")
#     FreqChn = request.form["FreqChn"]
#     ret = os.system("python fixed_freq.py")
#     if ret == 0:
#         return "QDD-Fixed-Freq-Test-log.csv"
#     else:
#         return "error"


# @module_bp.route('/charts')
# def charts():
#     data = np.random.randint(0, 100, size=(250, 2))
#     print(data.tolist())
#     return str(data.tolist())


# # @module_bp.route('/plot.png')
# # def plot_png():
# # fig = create_figure()
# # output = io.BytesIO()
# # FigureCanvas(fig).print_png(output)
# # return Response(output.getvalue(), mimetype='image/png')

# # plt = create_figure()
# # sio = io.BytesIO()
# # plt.savefig(sio, format='png')
# # # clear
# # plt.close('all')

# # # data = base64.encodebytes(sio.getvalue()).decode()
# # # print(data)
# # return Response(sio.getvalue(), mimetype='image/png')

# # def create_figure():
# #     # fig = Figure()
# #     # axis = fig.add_subplot(1, 1, 1)
# #     # xs = range(100)
# #     # ys = [random.randint(1, 50) for x in xs]
# #     # axis.plot(xs, ys)
# #     # return fig

# #     # np.random.seed(random.randint(1000, 5000))
# #     # N = 50
# #     # x = np.random.rand(N)
# #     # y = np.random.rand(N)
# #     # colors = np.random.rand(N)
# #     # area = (30 * np.random.rand(N))**2  # 0 to 15 point radii

# #     # plt.scatter(x, y, s=area, c=colors, alpha=0.5)
# #     # # plt.show()
# #     # return plt

# #     # demo 3
# #     # Fixing random state for reproducibility
# #     # np.random.seed(19680801)
# #     np.random.seed(random.randint(1000, 19680801))
# #     matplotlib.rcParams['axes.unicode_minus'] = False
# #     fig, ax = plt.subplots()
# #     ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
# #     ax.set_title('Plot Demo')
# #     # plt.show()
# #     return plt

# ##################################################
# # MOD DSP CORE VOLT
# ##################################################


# @module_bp.route('/api/get_dcv_reg', methods=['POST'])
# def get_dcv_reg():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     dcv = DspCoreVol(b)
#     dcv_reg = request.form["dcv_reg"]
#     if dcv_reg[0:2] == '0x' or dcv_reg[0:2] == '0X':
#         dcv_reg = int(dcv_reg, 16)
#     else:
#         dcv_reg = int(dcv_reg)
#     return str(hex(dcv.read(dcv_reg)))


# @module_bp.route('/api/set_dcv_reg', methods=['POST'])
# def set_dcv_reg():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     dcv = DspCoreVol(b)
#     dcv_reg = request.form["dcv_reg"]
#     dcv_reg_val = request.form["dcv_reg_val"]

#     if dcv_reg[0:2] == '0x' or dcv_reg[0:2] == '0X':
#         dcv_reg = int(dcv_reg, 16)
#     else:
#         dcv_reg = int(dcv_reg)

#     if dcv_reg_val[0:2] == '0x' or dcv_reg_val[0:2] == '0X':
#         dcv_reg_val = int(dcv_reg_val, 16)
#     else:
#         dcv_reg_val = int(dcv_reg_val)

#     dcv.write(int(dcv_reg), int(dcv_reg_val))
#     return "dcv set reg ok"


# @module_bp.route('/api/get_dcv_vol1', methods=['POST'])
# def get_dcv_vol1():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     dcv = DspCoreVol(b)
#     return str(round(dcv.buck1_vol, 4))


# @module_bp.route('/api/set_dcv_vol1', methods=['POST'])
# def set_dcv_vol1():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     dcv = DspCoreVol(b)
#     dcv_vol1 = request.form["dcv_vol1"]

#     dcv.buck1_vol = float(dcv_vol1)
#     return "dcv set vol ok"


# @module_bp.route('/api/get_dcv_vol2', methods=['POST'])
# def get_dcv_vol2():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     dcv = DspCoreVol(b)
#     return str(round(dcv.buck2_vol, 4))


# @module_bp.route('/api/set_dcv_vol2', methods=['POST'])
# def set_dcv_vol2():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     dcv = DspCoreVol(b)
#     dcv_vol2 = request.form["dcv_vol2"]

#     dcv.buck2_vol = float(dcv_vol2)
#     return "dcv set vol ok"


# @module_bp.route('/api/cosa_power', methods=['POST'])
# def cosa_power():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     cp = COSA(b)
#     cosa_power = int(request.form["cosa_power"])
#     cp.power = cosa_power
#     return "set cosa_power ok"


# @module_bp.route('/api/get_pops', methods=['POST'])
# def get_pops():
#     # 04h:196.7 = 1 
#     a.set_twi(1, 127, 0x04)
#     ret = a.get_twi(1, 196)
#     # '0b10000000'
#     if bin(int('0x' + ret.split(',')[0], 16))[2] == '0':
#         return "not supported"
#     else:
#         return "supported"

# @module_bp.route('/api/get_min_pop', methods=['POST'])
# def get_min_pop():
#     # 04h:198-199, big-endian S16, unit :0.01dBm, 
#     # i.e. -15dBm = 0xfa24, -1500 * 0.01dBm 
#     a.set_twi(1, 127, 0x04)
#     ret1 = a.get_twi(1, 198)
#     ret2 = a.get_twi(1, 199)
#     ret3 = int('0x' + ret1.split(',')[0] + ret2.split(',')[0] , 16)
#     ret = ctypes.c_int16(ret3).value
#     return "{} dBm".format(ret * 0.01)


# @module_bp.route('/api/get_max_pop', methods=['POST'])
# def get_max_pop():
#     # 04h:200-201, big-endian S16, unit :0.01dBm, 
#     #  i.e. -8dBm = 0xfce0, -800 * 0.01dBm 
#     a.set_twi(1, 127, 0x04)
#     ret1 = a.get_twi(1, 200)
#     ret2 = a.get_twi(1, 201)
#     ret3 = int('0x' + ret1.split(',')[0] + ret2.split(',')[0] , 16)
#     ret = ctypes.c_int16(ret3).value
#     return "{} dBm".format(ret * 0.01)


# @module_bp.route('/api/get_pop', methods=['POST'])
# def get_pop():
#     # 12h:200-201, big-endian S16, unit :0.01dBm, 
#     # i.e. -8dBm = 0xfce0, -800 * 0.01dBm 
#     a.set_twi(1, 127, 0x12)
#     ret1 = a.get_twi(1, 200)
#     ret2 = a.get_twi(1, 201)
#     ret3 = int('0x' + ret1.split(',')[0] + ret2.split(',')[0] , 16)
#     ret = ctypes.c_int16(ret3).value
#     return "{} dBm".format(ret * 0.01)


# @module_bp.route('/api/set_pop', methods=['POST'])
# def set_pop():
#     b = Broker()
#     pop_val = int(float(request.form["pop_val"])*100)
#     print(pop_val)
#     # 12h:200-201, big-endian S16, unit :0.01dBm, 
#     # i.e. -8dBm = 0xfce0, -800 * 0.01dBm 
#     a.set_twi(1, 127, 0x12)
#     b.twi_sbw(200, struct.pack('>h',pop_val)) 
#     return "set_pop, ok"


# ##################################################
# # MOD PIN
# ##################################################
# mod_pin_1_items = [['MCU1_DSP_SPI_CS', 1], ['MCU1_FLASH_SPI_CS', 1],
#                    ['MCU1_ADC3_SPI_CS', 1], ['ADC4_SPI_CS', 1],
#                    ['DSP_LINE_LOS', 1], ['CLK_SEC', 1],
#                    ['MODSELN_QSFPDD', 1], ['M_LPWN', 1], ['M_INT', 1],
#                    ['MCU2_MCU1_INTN_I', 1], ['MCU1_FLASH_RSTN', 1],
#                    ['MCU1_OUT_RST_N', 1], ['MCU1_DSP_RSTN', 1],
#                    ['P0V55_DSP_EN', 1], ['P1V8_DSP_EN', 1], ['P1V2_DSP_EN', 1],
#                    ['PS_EN', 1], ['COSA_VOFE_EN', 1], ['TX_DRIVER_VCC_EN', 1],
#                    ['P0V94_DSP_EN', 1], ['P0V75_DSP_EN', 1]
#                    ]

# mod_pin_2_items = [['MCU2_MCU1_INTN_O', 1], ['M_LPWN_ABC', 1],
#                    ['MCU2_ADC12_SPI_CS1', 1], ['MCU2_ADC12_SPI_CS2', 1],
#                    ['RX_TIA_BWH', 1], ['RX_TIA_BWL', 1], ['RX_TIA_SD', 1],
#                    ['RX_TIA_MC', 1], ['ITLA_OIF_MS_N', 1],
#                    ['ITLA_OIF_SRQ_N', 1], ['ITLA_OIF_DIS_N', 1],
#                    ['ITLA_OIF_RST_N', 1], ['RX_TIA_VCC_XY_EN', 1],
#                    ['COSA_VPD_EN', 1], ['P6V_EN', 1], ['COSA_PH_BIAS_EN', 1]
#                    ]

# mod_pin_3_items = [['M_BRETH_LED', 1], ['DSP_ALARM', 1],
#                    ['MCU1_RST_MCU2', 1], ['M_TX_VOA_QUICK_OFF_EN', 1],['M_MCU1_MCU2_RSVD', 1],
#                    ['S_TX_VOA_QUICK_OFF_EN', 1], ['S_BRETH_LED', 1], ['S_MCU1_MCU2_RSVD', 1],
                   
#                    ['TX_MPD_XY_SEL', 1], ['ITLA_EN', 1],
#                    ]


# @module_bp.route('/mod_pin')
# def pin():
#     return render_template('mod_pin.html',
#                            title='Module Pin Settings',
#                            mod_pin_1_items=mod_pin_1_items,
#                            mod_pin_2_items=mod_pin_2_items,
#                            mod_pin_3_items=mod_pin_3_items,
#                            for_customer=for_customer)


# @module_bp.route('/api/get_mod_pin_1')
# def get_mod_pin_1():
#     setdefaulttimeout(200000)
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     mod_pin_1_dict = {}
#     for item in mod_pin_1_items:
#         # print(item)
#         time.sleep(0.06)
#         d = DPin(b, item[0])
#         mod_pin_1_dict.update({item[0]: d.state})

#     # print('-------------------------')
#     # print(str(mod_pin_1_dict))
#     # print('-------------------------')
#     return json.dumps(mod_pin_1_dict)


# @module_bp.route('/api/set_mod_pin_1', methods=['POST'])
# def set_mod_pin_1():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     idx = request.form["idx"]
#     val = request.form["val"]
#     d = DPin(b, idx)
#     d.state = int(val)
#     return "set_mod_pin_1... ok"


# @module_bp.route('/api/get_mod_pin_2')
# def get_mod_pin_2():
#     setdefaulttimeout(200000)
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     mod_pin_2_dict = {}
#     for item in mod_pin_2_items:
#         # print(item)
#         time.sleep(0.06)
#         d = DPin(b, item[0])
#         mod_pin_2_dict.update({item[0]: d.state})

#     # print('-------------------------')
#     # print(str(mod_pin_2_dict))
#     # print('-------------------------')
#     return json.dumps(mod_pin_2_dict)


# @module_bp.route('/api/set_mod_pin_2', methods=['POST'])
# def set_mod_pin_2():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     idx = request.form["idx"]
#     val = request.form["val"]
#     d = DPin(b, idx)
#     d.state = int(val)
#     return "set_mod_pin_2... ok"


# @module_bp.route('/api/get_mod_pin_3')
# def get_mod_pin_3():
#     setdefaulttimeout(200000)
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     mod_pin_3_dict = {}
#     for item in mod_pin_3_items:
#         # print(item)
#         time.sleep(0.06)
#         d = DPin(b, item[0])
#         mod_pin_3_dict.update({item[0]: d.state})

#     return json.dumps(mod_pin_3_dict)


# @module_bp.route('/api/set_mod_pin_3', methods=['POST'])
# def set_mod_pin_3():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     idx = request.form["idx"]
#     val = request.form["val"]
#     d = DPin(b, idx)
#     d.state = int(val)
#     return "set_mod_pin_3... ok"


# ##################################################
# # MOD ADC
# ##################################################
# adc_items = [['TX_DRIVER_PI_XI', 'V'], ['TX_DRIVER_PI_XQ', 'V'],
#              ['TX_DRIVER_PI_YI', 'V'], ['TX_DRIVER_PI_YQ', 'V'],
#              ['COSA_TEMP_OUT', '℃'], ['TX_DRV_VOCM', 'V'],
#              ['RX_TIA_PI_XI', 'V'], ['VOFE_CURRENT_SEN', 'A'],
#              ['MCU1_RX_TIA_PI_YI', 'V'], ['TX_VOA_X', 'V'], ['TX_VOA_Y', 'V'],
#              ['REF2V5_MCU_ABC', 'V'], ['TX_VOA_X_I', 'V'], ['TX_VOA_Y_I', 'V'],
#              ['MCU1INTERNAL_TEMP_SNS', 'V'], ['MCU1INTERNAL_AVDD', 'V'],
#              ['MCU1INTERNAL_IOVDD0', 'V'], ['MCU1INTERNAL_IOVDD1', 'V'],
#              ['P0V55_DSP_VDDC', 'V'], ['P0V75_DSP_VDDM', 'V'],
#              ['P0V94_DSP_VDDA', 'V'], ['P1V8_DSP_VDDA18', 'V'],
#              ['P1V2_DSP_VDDA12', 'V'], ['P3V_ABC_TXMPD', 'V'],
#              ['PCB_TEMP_ADC', '℃'], ['DSP_TEMP', '℃'],
#              ['POST_MPDX_DC_MCU2ADC', 'V'], ['POST_MPDY_DC_MCU2ADC', 'V'],
#              ['POST_MPDXY_AC_MCU2ADC', 'V'], ['RX_VOA_X', 'V'],
#              ['TIA_PD_BIAS', 'V'], ['TIA_VCC', 'V'], ['RX_VOA_Y', 'V'],
#              ['RX_MPD_X_MCU2', 'V'], ['RX_TIA_PI_XQ', 'V'],
#              ['RX_TIA_PI_YI', 'V'], ['RX_TIA_PI_YQ', 'V'], ['RX_VOA_X_I', 'V'],
#              ['RX_MPD_Y_MCU2', 'V'], ['RX_VOA_Y_I', 'V'],
#              ['MCU2INTERNAL_TEMP_SNS', 'V'], ['MCU2INTERNAL_AVDD', 'V'],
#              ['MCU2INTERNAL_IOVDD0', 'V'], ['MCU2INTERNAL_IOVDD1', 'V'],
#              ['ADC_TIA_VGC_YQ', 'V'], ['ADC_TIA_VGC_YI', 'V'],
#              ['ADC_TIA_VGC_XQ', 'V'], ['ADC_TIA_VGC_XI', 'V'],
#              ['TX_DRV_VCC', 'V'], ['P5V8_DRIVER_VOFE', 'V'], ['P6V_VOA', 'V'],
#              ['COSA_PH_BIAS', 'V']]


# @module_bp.route('/mod_adc')
# def mod_adc():
#     return render_template('mod_adc.html',
#                            title='Module ADC',
#                            adc_items=adc_items,
#                            for_customer=for_customer)


# @module_bp.route('/api/get_adc', methods=['POST'])
# def get_adc():
#     setdefaulttimeout(200000)
#     item = request.form["item"]
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     item_list = [
#         'TX_VOA_X', 'TX_VOA_X_I', 'TX_VOA_Y', 'TX_VOA_Y_I', 'RX_VOA_X',
#         'RX_VOA_X_I', 'RX_VOA_Y', 'RX_VOA_Y_I', 'RX_MPD_X_MCU2', 'RX_MPD_Y_MCU2'
#     ]
#     a = Ain(b, item)
#     if item in item_list:
#         val_a = a.val_a
#         cells_val = str(val_a[0]) + ',' + str(round(val_a[1], 6)) + ',' + str(round(val_a[2], 6))
#     else:
#         val = a.val
#         cells_val = str(val[0]) + ',' + str(round(val[1], 3)) + ',' + str(round(val[2], 3))

#     return cells_val


# @module_bp.route('/api/get_adc_all', methods=['POST'])
# def get_adc_all():
#     setdefaulttimeout(200000)
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     item_list = [
#         'TX_VOA_X', 'TX_VOA_X_I', 'TX_VOA_Y', 'TX_VOA_Y_I', 'RX_VOA_X',
#         'RX_VOA_X_I', 'RX_VOA_Y', 'RX_VOA_Y_I', 'RX_MPD_X_MCU2', 'RX_MPD_Y_MCU2'
#     ]

#     adc_dict = {}
#     for item in adc_items:
#         a = Ain(b, item[0])
#         if item[0] in item_list:
#             val_a = a.val_a
#             cells_val = str(val_a[0]) + ',' + str(round(val_a[1], 6)) + ',' + str(round(val_a[2], 6))
#         else:
#             val = a.val
#             cells_val = str(val[0]) + ',' + str(round(val[1], 3)) + ',' + str(round(val[2], 3))

#         adc_dict.update({item[0]: cells_val})

#     print(adc_dict)
#     return json.dumps(adc_dict)


# ##################################################
# # MOD DAC
# ##################################################
# dac_items = [['DRIVER_VGC_XI', 'V'], ['DRIVER_VGC_YI', 'V'],
#              ['DRIVER_VGC_XQ', 'V'], ['DRIVER_VGC_YQ', 'V'],
#              ['MCU1_TX_VOA_X', 'mA'], ['MCU1_TX_VOA_Y', 'mA'],
#              ['DRIVER_VT', 'V'], ['MCU1_DAC_TX_PN_BIAS', 'V'],
#              ['COSA_VOFE_FB', 'V'], ['P0V55_DSP_FB', 'V'],
#              ['MCU2_TXIH1_AC', 'V'], ['MCU2_TXIH1_DC', 'V'],
#              ['MCU2_TXQH1_DC', 'V'], ['MCU2_TYIH1_DC', 'V'],
#              ['MCU2_TYQH1_DC', 'V'], ['MCU2_TXQH1_AC', 'V'],
#              ['MCU2_TYIH1_AC', 'V'], ['MCU2_TYQH1_AC', 'V'],
#              ['MCU2_TXPH1_DC', 'V'], ['MCU2_TYPH1_DC', 'V'],
#              ['MCU2_TXPH1_AC', 'V'], ['MCU2_TYPH1_AC', 'V'],
#              ['DAC_TIA_VOA_YI', 'V'], ['DAC_TIA_VOA_XI', 'V'],
#              ['DAC_TIA_VOA_YQ', 'V'], ['DAC_TIA_VOA_XQ', 'V'],
#              ['DAC_RX_VOA_X', 'mA'], ['DAC_RX_VOA_Y', 'mA'],
#              ['DAC_RX_IQ_PH_X', 'V'], ['DAC_RX_IQ_PH_Y', 'V'],
#              ['ABC_VGA_R', 'Ω']]


# @module_bp.route('/mod_dac')
# def mod_dac():
#     return render_template('mod_dac.html',
#                            title='Module DAC',
#                            dac_items=dac_items,
#                            for_customer=for_customer)


# @module_bp.route('/api/get_dac', methods=['POST'])
# def get_dac():
#     setdefaulttimeout(200000)
#     item = request.form["item"]
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     a = Aout(b, item)
#     # cells_val =  str(round(a.aval,2)) + ',' + str(a.dval)
#     cells_val = str(round(a.aval, 4)) + ',' + str(a.dval) + ',' + str(
#         round(a.raw_aval, 4))
#     return cells_val



# @module_bp.route('/api/get_dac_all', methods=['POST'])
# def get_dac_all():
#     setdefaulttimeout(200000)
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     dac_dict = {}
#     for item in dac_items:
#         a = Aout(b, item[0])
#         cells_val = str(round(a.aval, 4)) + ',' + str(a.dval) + ',' + str(round(a.raw_aval, 4))
#         dac_dict.update({item[0]: cells_val})
#         time.sleep(0.01)

#     print(dac_dict)
#     return json.dumps(dac_dict)



# @module_bp.route('/api/set_dac', methods=['POST'])
# def set_dac():
#     setdefaulttimeout(200000)
#     item = request.form["item"]
#     dac_phy_val = request.form["dac_phy_val"]

#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     a = Aout(b, item)
#     a.aval = float(dac_phy_val)
#     return "set_dac ok"


# ##################################################
# # MOD ITLA
# ##################################################
# @module_bp.route('/mod_itla')
# def mod_itla():
#     return render_template('mod_itla.html', title='ITLA Settings',for_customer=for_customer)


# @module_bp.route('/api/get_rel_info', methods=['GET', 'POST'])
# def get_rel_info():
#     b = Broker()
#     laser = Laser(b)
#     return str((laser.release).decode())


# @module_bp.route('/api/get_itla_current_values', methods=['GET', 'POST'])
# def get_itla_current_values():
#     b = Broker()
#     laser = Laser(b)
#     # get_cur_frequency = laser.get_cur_frequency()
#     # get_cur_power = laser.get_cur_power()
#     # get_temperature = laser.get_temperature()
#     # return str(get_cur_frequency) + ',' + str(get_cur_power) + ',' + str(
#     #     get_temperature)

#     # frequency = laser.frequency
#     # power = laser.power
#     # temp = laser.temp
#     # fcf = laser.fcf
#     # lff = laser.lff
#     # llf = laser.llf
#     # ftf = laser.ftf
#     # grid = laser.grid
#     # channel = laser.channel
#     # release = laser.release
#     return str(laser.frequency) + ',' + str(laser.power) + ',' + str(
#         laser.temp) + ',' + str(laser.fcf) + ',' + str(laser.lff) + ',' + str(
#             laser.llf) + ',' + str(laser.ftf) + ',' + str(
#                 laser.grid) + ',' + str(laser.channel)
#     # return str(laser.frequency) + ',' + str(laser.power) + ',' + str(laser.temp) + ',' + str(laser.fcf) + ',' + str(laser.lff) + ',' + str(laser.llf) + ',' + str(laser.ftf) + ',' + str(laser.grid) + ',' + str(laser.channel) + ',' + '---'


# @module_bp.route('/api/get_itla_reg', methods=['GET', 'POST'])
# def get_itla_reg():
#     b = Broker()
#     laser = Laser(b)
#     itla_reg_p1 = str(request.form["itla_reg_p1"])
#     return str(laser.read(int(itla_reg_p1, 16)))


# @module_bp.route('/api/set_itla_reg', methods=['GET', 'POST'])
# def set_itla_reg():
#     b = Broker()
#     laser = Laser(b)
#     itla_reg_p1 = str(request.form["itla_reg_p1"])
#     itla_reg_p2 = str(request.form["itla_reg_p2"])
#     laser.write(int(itla_reg_p1, 16), int(itla_reg_p2))
#     return "btn_set_itla_reg ok"


# @module_bp.route('/api/set_itla_status', methods=['POST'])
# def set_itla_status():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     itla_status = str(request.form["itla_status"])
#     # ITLA_OIF_DIS_N
#     # ITLA_OIF_RST_N

#     if itla_status == '1':
#         d = DPin(b, 'ITLA_OIF_DIS_N')
#         d.state = 1
#         # d = DPin(b, 'ITLA_OIF_RST_N')
#         # d.state = 1
#     else:
#         d = DPin(b, 'ITLA_OIF_DIS_N')
#         d.state = 0
#         # d = DPin(b, 'ITLA_OIF_RST_N')
#         # d.state = 0

#     return "btn_set_itla_status ok"


# @module_bp.route('/api/get_itla_status', methods=['GET', 'POST'])
# def get_itla_status():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     # d1 = DPin(b, 'ITLA_OIF_RST_N')
#     d2 = DPin(b, 'ITLA_OIF_DIS_N')

#     # if d1.state == 1 and d2.state == 1:
#     if d2.state == 1:
#         return str(1)
#     else:
#         return str(0)


# # @module_bp.route('/api/set_itla_settings_freq', methods=['GET', 'POST'])
# # def set_itla_settings_freq():
# #     b = Broker()
# #     laser = Laser(b)
# #     itla_settings_freq = request.form["itla_settings_freq"]
# #     laser.frequency_setting(float(itla_settings_freq))
# #     return "set_itla_settings_freq ok : " + str(itla_settings_freq)


# @module_bp.route('/api/set_itla_settings_channel', methods=['GET', 'POST'])
# def set_itla_settings_channel():
#     b = Broker()
#     laser = Laser(b)
#     itla_settings_channel = request.form["itla_settings_channel"]
#     # laser.channel_setting(int(itla_settings_channel))
#     laser.channel = int(itla_settings_channel)
#     return "set_itla_settings_channel ok : " + str(itla_settings_channel)


# @module_bp.route('/api/set_itla_settings_power', methods=['GET', 'POST'])
# def set_itla_settings_power():
#     b = Broker()
#     laser = Laser(b)
#     itla_settings_power = request.form["itla_settings_power"]
#     # laser.power_setting(float(itla_settings_power))
#     laser.power = float(itla_settings_power)
#     return "set_itla_settings_power ok : " + str(itla_settings_power)


# @module_bp.route('/api/set_itla_settings_grid', methods=['GET', 'POST'])
# def set_itla_settings_grid():
#     b = Broker()
#     laser = Laser(b)
#     itla_settings_grid = request.form["itla_settings_grid"]
#     # laser.grid_setting(float(itla_settings_grid))
#     laser.grid = float(itla_settings_grid)
#     return "set_itla_settings_grid ok : " + str(itla_settings_grid)


# @module_bp.route('/api/set_itla_settings_fcf', methods=['GET', 'POST'])
# def set_itla_settings_fcf():
#     b = Broker()
#     laser = Laser(b)
#     itla_settings_fcf = request.form["itla_settings_fcf"]
#     laser.fcf = int(itla_settings_fcf)
#     return "set_itla_settings_fcf ok : " + str(itla_settings_fcf)


# @module_bp.route('/api/set_itla_settings_ftf', methods=['GET', 'POST'])
# def set_itla_settings_ftf():
#     b = Broker()
#     laser = Laser(b)
#     itla_settings_ftf = request.form["itla_settings_ftf"]
#     laser.ftf = int(itla_settings_ftf)
#     return "set_itla_settings_ftf ok : " + str(itla_settings_ftf)


# @module_bp.route('/api/set_itla_settings_wavelength', methods=['GET', 'POST'])
# def set_itla_settings_wavelength():
#     b = Broker()
#     cmis= CMIS(b)
#     wavelength = float(request.form["itla_settings_wavelength"])
#     print("set_itla_settings_wavelength ...", wavelength)

#     b.twi_bw(127, 0x10)
#     b.twi_bw(128, 1)
#     while True:
#         Datapath_state = cmis.dp_state
#         if  Datapath_state != 1:
#         # self.osfpcmis.dp_state
#             time.sleep(0.5)
#         else:
#             break

#     channel=round(float(wavelength-193.1)/0.1)
#     b.twi_bw(127, 0x12)   #change wavelength through CMIS 
#     b.twi_bw(136, (channel>>8 & 0xff))
#     b.twi_bw(137, channel & 0xff)
#     b.twi_bw(127, 0x10)
#     b.twi_bw(128, 0)
#     while True:
#         Datapath_state = cmis.dp_state
#         print("Datapath_state ", Datapath_state)
#         if  Datapath_state != 4:
#             time.sleep(0.5)
#         else:
#             break

#     return "set_itla_settings_wavelength ok : " + str(wavelength)

# ##################################################
# # MOD ADC
# ##################################################
# abc_items = [['XP', 0], ['XI', 1], ['XQ', 2], ['YP', 3], ['YI', 4], ['YQ', 5]]


# @module_bp.route('/mod_abc')
# def mod_abc():
#     return render_template('mod_abc.html',
#                            title='Module ABC Settings',
#                            abc_items=abc_items,for_customer=for_customer)



# # dsp api suggest style ! for test only ------begin
# @module_bp.route('/mod_dsp_suggest')
# def mod_dsp_suggest():
#     return render_template('mod_dsp_suggest.html', title='DSP API Settings (suggest)',for_customer=for_customer)



# apis_list= [
# "enable_fw_support(support)",
# "check_api_compatibility(self)",
# "Echo(data)",
# "ControlTask(bRoutineSelect,bAction,Reserved)",
# "ExceptionBacktrace(processorId,aReserved)",
# "Hlupgrade(action)",
# "ReadRegister(address)",
# "WriteRegister(address,value)",
# "UpdateOneRegister(address,value,mask)",
# "ReadFirmwareInformation()",
# "GetGpio(gpio_id)",
# "SetGpio(gpio_id,gpio_direction,gpio_status)",
# "GetChipId()",
# "SetGpioMap(register_addr,gpio_id,bit_number,gpio_direction)",
# "GetGpioMap(gpio_id)",
# "SetBerThresholdToGpio(ber_threshold_base,ber_threshold_exp,host_ber_threshold_base,host_ber_threshold_exp,line_gpio_id,host_gpio_id)",
# "SetEthernetAlarmsToGpio(gpio_id,channel,alarms_direction,alarms_select,operation,enable)",
# "GetEthernetAlarmsToGpio(gpio_id)",
# "SetTransceiverMode(reserved_0,line_fec,pilot_symbol_separation,line_shaping,line_modulation,bcd_mode,ltx_osr,lrx_osr,reserved_1,signal_type,line_mapping,host_modulation)",
# "SetLoopbackMode(lpbk_mode,channel,enable)",
# "GetLoopbackMode(lpbk_mode,channel)",
# "SetHostBallMap(hrx_mapping,htx_mapping)",
# "SetHostDynamicReprovisioning(channel,signal_type)",
# "GetTransceiverMode()",
# "GetHostBallMap()",
# "SetOpticalMonitorTriggerSource(trigger_source,interval)",
# "SetPerformanceMonitorTriggerSource(trigger_source)",
# "GetOpticalMonitorTriggerSource()",
# "GetPerformanceMonitorTriggerSource()",
# "TriggerMonitors()",
# "SetPcsMode(channel,mode)",
# "GetPcsMode(channel)",
# "GetCfecFrameSize(channel,direction)",
# "ReStartLineIngressDsp(action)",
# "ResetTransceiver(path)",
# "SetClientSwap(direction,clients)",
# "GetClientSwap(direction)",
# "SetEthernetFec(channel,bypass_correction_enable,bypass_indication_enable)",
# "GetEthernetFec(channel)",
# "SetOtnOhpHardwareAlarmsInterfacesConfig(channel,map_level,hardware_pin_select,ddeg_bus,dtim_bus,diae_bus,dbiae_bus,dbdi_bus,dltc_bus,dais_bus,doci_bus,dlck_bus,dmsim,dplm,dcsf)",
# "GetOtnOhpHardwareAlarmsInterfacesConfig(channel,map_level,hardware_pin_select)",
# "SetOtnHardwareAlarmsInterfacesConfig(channel,direction,hardware_pin_select,otu_dloflane,otu_dlol,otu_dlof,otu_dlom)",
# "GetOtnHardwareAlarmsInterfacesConfig(channel,direction,hardware_pin_select)",
# "SetOtnGmpHardwareAlarmsInterfacesConfig(channel,hardware_pin_select,odu_map1_dloflom,odu_map2_dloflom,gmp_host_dloomfi,gmp_map1_dloomfi,gmp_map2_dloomfi)",
# "GetOtnGmpHardwareAlarmsInterfacesConfig(channel,hardware_pin_select)",
# "SetEthernetHardwareAlarmsInterfacesConfig(channel,direction,hardware_pin_select,pcs_align_status_n,pcs_lf_detected,pcs_rf_detected,pcs_hi_ber,pcs_hi_ser,pcs257_am_lock_n,pcs66_block_lock_n,pcs66_am_lock_n)",
# "GetEthernetHardwareAlarmsInterfacesConfig(channel,direction,hardware_pin_select)",
# "GetFlexOHardwareAlarmsInterfacesConfig(channel,hardware_pin_select)",
# "SetFlexOHardwareAlarmsInterfacesConfig(channel,hardware_pin_select,flexo_dlol,flexo_dlom,flexo_dloflom,flexo_drdi,flexo_dgidm,flexo_dpmm)",
# "GetFlexEHardwareAlarmsInterfacesConfig(channel,direction,hardware_pin_select)",
# "SetFlexEHardwareAlarmsInterfacesConfig(channel,direction,hardware_pin_select,flexe_drdi,flexe_dgidm,flexe_dpmm,flexe_dlof,flexe_dlom)",
# "SetGmpConsequentActionConfig(channel,map_level,gmp_dloomfi_ca_enable,ohp_dplm_ca_enable)",
# "GetGmpConsequentActionConfig(channel,map_level)",
# "SetEthernetConsequentActionsConfig(channel,direction,pcs_lf_detected_ca_enable,pcs_rf_detected_ca_enable,pcs_hi_ber_ca_enable,pcs_hi_ser_ca_enable)",
# "GetEthernetConsequentActionsConfig(channel,direction)",
# "SetFlexOConsequentActionsConfig(channel,flexo_drdi_ca_enable,flexo_dgidm_ca_enable,flexo_dpmm_ca_enable)",
# "GetFlexOConsequentActionsConfig(channel)",
# "SetEnableConsequentActions(channel,direction,ca_enable)",
# "GetEnableConsequentActions(channel,direction)",
# "SetEthernetMaintenanceSignalConfig(channel,egress_maintenance_signal,ingress_maintenance_signal)",
# "GetEthernetMaintenanceSignalConfig(channel)",
# "GetOtnOhpPmCounters(channel,map_level,layer_level)",
# "SetFlexoGroupConfig(channel_sync)",
# "GetFlexoGroupConfig()",
# "GetFlexOOhpSinkFieldsAccepted(channel)",
# "SetPcsFramePauseConfig(frame_pause_source_address,frame_pause_destination_address,frame_pause_enable,frame_pause_time_override_enable,frame_pause_time_override_value,frame_pause_gap_override_enable,frame_pause_gap_override_value)",
# "GetPcsFramePauseConfig()",
# "SetPcsMlgAlignmentMarkers(channel,lane_marker)",
# "GetPcsMlgAlignmentMarkers(channel)",
# "SetEthernetIdleTrafficTimer(channel,timer_value)",
# "GetEthernetIdleTrafficTimer(channel)",
# "SetEthernetIdleTrafficTimerDirection(path)",
# "GetEthernetIdleTrafficTimerDirection()",
# "SetOtnMaintenanceSignalConfig(channel,maintenance_signal)",
# "GetOtnMaintenanceSignalConfig(channel)",
# "SetFlexOMaintenanceSignalConfig(channel,maintenance_signal)",
# "GetFlexOMaintenanceSignalConfig(channel)",
# "GetOtnOhpSinkMsiConsequentActionConfig(channel,map_level)",
# "SetOtnOhpSinkMsiConsequentActionConfig(channel,map_level,msim_ca_enable)",
# "GetOtnOhpSinkCsfConsequentActionConfig(channel)",
# "SetOtnOhpSinkCsfConsequentActionConfig(channel,csf_ca_enable)",
# "SetOtnOtucAis(direction,otuc_ais_enable)",
# "GetOtnOtucAis(direction)",
# "SetOverrideDefaultConfig(param_index,value)",
# "GetLineEgressLowSrLaneAttenuation(lane)",
# "SetLineEgressLowSrLaneAttenuation(lane,attenuation)",
# "SetLineEgressLowSrFilterCoefficients(lane,coefficients)",
# "GetLineEgressLowSrFilterCoefficients(lane)",
# "SetLineEgressLowSrLaneSkew(lane,skew,reserved)",
# "GetLineEgressLowSrLaneSkew(lane)",
# "SetLineEgressHighSrFilterCoefficients(lane,coefficients)",
# "GetLineEgressHighSrFilterCoefficients(lane)",
# "GetLineEgressHighSrLaneSkew(lane)",
# "SetLineEgressHighSrLaneSkew(lane,skew)",
# "SetLineEgressHighSrPulseShaping(lane,roll_off_factor,pulse_shaping_filter)",
# "SetLineEgressHighSrPreEmphasis(lane,coefficients,enable)",
# "SetLineEgressHighSrLaneAmplitude(lane,amplitude)",
# "GetLineEgressHighSrLaneAmplitude(lane)",
# "SetLineEgressLaneReassignment(lane_0,lane_1,lane_2,lane_3)",
# "GetLineEgressLaneReassignment()",
# "GetLineEgressHighSrPulseShaping(lane)",
# "GetLineEgressHighSrPreEmphasis(lane)",
# "SetLineEgressLaneMute(lane,mute)",
# "GetLineEgressLaneMute(lane)",
# "SetLineEgressLanePolarity(lane,polarity)",
# "GetLineEgressLanePolarity(lane)",
# "SetLineEgressHighSrFrequencyMaskBoost(lane,frequency_bin,gain,frequency_mask_width)",
# "SetLineEgressLaneAnalogAttenuation(lane,attenuation)",
# "GetLineEgressLaneAnalogAttenuation(lane)",
# "GetLineSymbolRate()",
# "SetLTxFilter(coeffs,polarization)",
# "GetLTxFilter(polarization)",
# "GetLineIngressDspStatus()",
# "SetLineIngressCcrBypass(enable)",
# "GetLineIngressCcrBypass()",
# "SetLineIngressSkew(polarization,skew_phase_i)",
# "GetLineIngressSkew(polarization)",
# "SetLineIngressMatrixRotator(coefficients,mtr_mode,bypass)",
# "GetLineIngressMatrixRotator()",
# "SetLineIngressFleCdRange(min_cd,max_cd)",
# "GetLineIngressBcdFilter()",
# "SetLineIngressBcdFilter(roll_off_factor,pulse_shaping_filter)",
# "GetBcdPowerLim()",
# "SetBcdPowerLim(enable,cd,reserved_1,reserved_2)",
# "SetLineIngressBps(window_h,window_v,bypass)",
# "GetLineIngressBps()",
# "GetLineIngressAgcStatus()",
# "SetLineIngressAgcConfig(lane,signal_reference,signal_gain,signal_max,signal_min,enable)",
# "GetLineIngressAgcConfig(lane)",
# "SetLineIngressLosConfig(lane,signal_detect_dn,signal_detect_up,signal_detect_high,mode,enable)",
# "GetLineIngressLosConfig(lane)",
# "GetLineIngressFleCdRange()",
# "GetFFECoefficients(init,selection_filter,real_img,high_low)",
# "SetLineIngressLosSource(los_source)",
# "GetLineIngressLosSource()",
# "SetRxSkewCalConfig(latency,average_samples_amount,iterations_per_pol)",
# "GetHostEgressLanePolarity()",
# "SetHostEgressLanePolarity(polarity)",
# "GetHostHistogram(lane)",
# "RelinkHostEgress(lane)",
# "GetHostRxStatus(lane)",
# "GetHostEgressLaneStatus(lane)",
# "GetHostPulseResponse(lane)",
# "SetHostFastRelockMode(fast_relock_mode)",
# "GetHostFastRelockMode()",
# "SetHostDemapPll(channel,start_ki,start_kp,steady_ki,steady_kp,swap_timer,reserved)",
# "GetHostDemapPll(channel)",
# "GetEgressSmInformation(channel)",
# "GetHostIngressLanePolarity()",
# "SetHostIngressLanePolarity(polarity)",
# "SetHostIngressLaneMute(dual,mute)",
# "GetHostIngressLaneMute(dual)",
# "SetHostIngressFilterCoefficients(lane,coefficients,low_eye,high_eye)",
# "GetHostIngressFilterCoefficients(lane)",
# "SetAutomaticHtxSquelch(htx_squelch)",
# "GetAutomaticHtxSquelch()",
# "SetOtnOhpSourcePt(channel,map_level,payload_type_value,payload_type_enable)",
# "GetOtnOhpSourcePt(channel,map_level)",
# "SetOtnOhpSinkDdegThreshold(channel,map_level,layer_level,degraded_threshold,accum_good_seconds,accum_bad_seconds)",
# "GetOtnOhpSinkDdegThreshold(channel,map_level,layer_level)",
# "SetOtnOhpSourceFtfl(channel,map_level,ftfl_value,ftfl_enable)",
# "GetOtnOhpSourceFtfl(channel,map_level)",
# "SetOtnOhpLayerReorder(channel,map_level,layer_level_reorder_array)",
# "GetOtnOhpLayerReorder(channel,map_level)",
# "SetOtnOhpSinkMode(channel,map_level,layer_level,layer_mode,tim_action_enable,ltc_action_enable)",
# "GetOtnOhpSinkMode(channel,map_level,layer_level)",
# "SetOtnOhpDmMode(channel,map_level,dm_subfield,dm_mode)",
# "GetOtnOhpDmMode(channel,map_level,dm_subfield)",
# "RunOtnOhpDm(channel,map_level,dm_subfield,dm_action)",
# "SetOtnOhpSourceBip8(channel,map_level,layer_level,mode)",
# "SetOtnOhpSourceBdi(channel,map_level,layer_level,mode,override_enable,override_value)",
# "SetOtnOhpSourceBeiBiae(channel,map_level,layer_level,mode,override_enable,override_value)",
# "SetOtnOhpSourceStat(channel,map_level,layer_level,mode,override_enable,override_value)",
# "GetOtnOhpSourceBip8(channel,map_level,layer_level)",
# "GetOtnOhpSourceBdi(channel,map_level,layer_level)",
# "GetOtnOhpSourceBeiBiae(channel,map_level,layer_level)",
# "GetOtnOhpSourceStat(channel,map_level,layer_level)",
# "SetFlexOOhpSourceMode(channel,phy_map_value,gid_value,pid_value,avail_value)",
# "GetFlexOOhpSourceMode(channel)",
# "SetFlexOOhpSinkFieldsExpected(channel,phy_map_expected,gid_expected,pid_expected)",
# "GetFlexOOhpSinkFieldsExpected(channel)",
# "SetFlexEOhpSinkFieldsExpected(channel,direction,phy_map_expected,gid_expected,pid_expected)",
# "GetFlexEOhpSinkFieldsExpected(channel,direction)",
# "GetFlexEOhpSinkFieldsAccepted(channel,direction)",
# "SetOtnOhpSourceApsChannels(channel,map_level,aps_channel_select,aps_value,aps_enable)",
# "GetOtnOhpSourceApsChannels(channel,map_level,aps_channel_select)",
# "SetOtnOhpSourceTti(channel,field_level,map_level,tti_sapi,tti_dapi,tti_os,enable)",
# "GetOtnOhpSourceTti(channel,field_level,map_level)",
# "GetOtnOhpSinkTtiAccepted(channel,field_level,map_level)",
# "GetOtnOhpSinkTtiExpected(channel,field_level,map_level)",
# "SetOtnOhpSinkTtiExpected(channel,field_level,map_level,tti_sapi_expected,tti_dapi_expected,tti_os_expected,tti_sapi_expected_mask,tti_dapi_expected_mask,tti_os_expected_mask)",
# "GetOtnOhpSinkPtExpected(channel,map_level)",
# "SetOtnOhpSinkPtExpected(channel,map_level,payload_type_expected)",
# "GetOtnOhpSinkPtAccepted(channel,map_level)",
# "GetOtnOhpSinkApsChannels(channel,map_level,aps_channel_select)",
# "GetOtnOhpSinkFtflAcceptedMask(channel,map_level)",
# "SetOtnOhpSinkFtflAcceptedMask(channel,map_level,ftfl_mask)",
# "GetOtnOhpSinkFtflAccepted(channel,map_level)",
# "SetOtnOhpSinkMsiExpected(channel,map_level,msi_expected,msi_expected_mask)",
# "GetOtnOhpSinkMsiExpected(channel,map_level)",
# "GetOtnOhpSinkMsiAccepted(channel,map_level)",
# "SetOtnOhpSourceMsi(channel,map_level,msi_value,msi_enable)",
# "GetOtnOhpSourceMsi(channel,map_level)",
# "SetOtnOhpSourceCsf(channel,map_level,csf_mode,csf_override_value,csf_override_enable)",
# "GetOtnOhpSourceCsf(channel,map_level)",
# "SetOhaGlobalConfig(sgmii_channel,sgmii_rate,lpbk_mode,rx_discard_on_address_mismatch,tx_mac_src_address,tx_mac_dst_address)",
# "GetOhaGlobalConfig(sgmii_channel)",
# "GetOhaGlobalStatus(sgmii_channel)",
# "SetOtnOhaConfig(channel,map_level,sgmii_channel,add_byte_select,add_byte_mask,add_mfas_align,drop_byte_select,drop_ohbu_length,port_enable)",
# "GetOtnOhaConfig(channel,map_level)",
# "SetFlexeOhaConfig(channel,sgmii_channel,drop_ohbu_length,add_pcs_mask,port_enable)",
# "GetFlexeOhaConfig(channel)",
# "SetFlexoOhaConfig(channel,sgmii_channel,add_byte_select,add_byte_mask,drop_byte_select,drop_ohbu_length,mfas_insertion_enable,port_enable)",
# "GetFlexoOhaConfig(channel)",
# "SetOhaFw(action)",
# "GetOhaFw()",
# "LoadOhaFw(data)",
# "GetOhaFwVersion()",
# "GetOhaSnr(sgmii_channel)",
# "RestartOha()",
# "SetPcsTestPatternGeneratorConfig(channel,direction,pcs_signal_type,enable)",
# "GetPcsTestPatternGeneratorConfig(channel,direction)",
# "SetPcsTestPatternCheckerConfig(channel,direction,pcs_signal_type,enable)",
# "GetPcsTestPatternCheckerConfig(channel,direction)",
# "SetOtuServerTestPatternGeneratorConfig(channel,signal_type,enable)",
# "SetOtuServerTestPatternCheckerConfig(channel,signal_type,enable)",
# "SetCoreCfecTestPatternCheckerConfig(signal_type,enable)",
# "SetCoreCfecTestPatternGeneratorConfig(signal_type,enable)",
# "GetCoreCfecTestPatternCheckerConfig()",
# "GetCoreCfecTestPatternGeneratorConfig()",
# "SetLineCfecEvmTestPatternGeneratorConfig(signal_type,enable)",
# "GetLineCfecEvmTestPatternGeneratorConfig()",
# "SetHostUnframedTestPatternGeneratorConfig(dual,prbs_type_1,prbs_type_2,enable)",
# "GetHostUnframedTestPatternGeneratorConfig(dual)",
# "SetHostUnframedTestPatternCheckerConfig(dual,prbs_type_1,prbs_type_2,enable)",
# "GetHostUnframedTestPatternCheckerConfig(dual)",
# "GetOtuServerTestPatternGeneratorConfig(channel)",
# "GetOtuServerTestPatternCheckerConfig(channel)",
# "SetOtuClientTestPatternGeneratorConfig(channel,direction,signal_type,keep_incoming_fs,enable)",
# "SetOtuClientTestPatternCheckerConfig(channel,direction,signal_type,enable)",
# "GetOtuClientTestPatternGeneratorConfig(channel,direction)",
# "GetOtuClientTestPatternCheckerConfig(channel,direction)",
# "SetHostUnframedStandardPatternGeneratorConfig(dual,standard_type_1,standard_type_2,enable)",
# "GetHostUnframedStandardPatternGeneratorConfig(dual)",
# "SetHostUnframedCustomPatternGeneratorConfig(dual,fixed_pattern_1,fixed_pattern_2,enable)",
# "GetHostUnframedCustomPatternGeneratorConfig(dual)",
# "SetHostUnframedCustomPatternCheckerConfig(dual,fixed_pattern_1,fixed_pattern_2,enable)",
# "GetHostUnframedCustomPatternCheckerConfig(dual)",
# "GetHostUnframedTestPatternCheckerStatistics(lane)",
# "SetLineSdfecUnframedTestPatternGeneratorConfig(pattern,seed,enable)",
# "GetLineSdfecUnframedTestPatternGeneratorConfig()",
# "SetLineSdfecUnframedTestPatternCheckerConfig(pattern,enable)",
# "GetLineSdfecUnframedTestPatternCheckerConfig()",
# "GetLineSdfecUnframedTestPatternCheckerCounters()",
# "SetLineSdfecCustomPatternGeneratorConfig(pattern,enable)",
# "GetLineSdfecCustomPatternGeneratorConfig()",
# "GetCoreCfecTestPatternCheckerStatistics()",
# "GetIngressSmInformation()",
# "GetDisruptionTime()",
# "GetIngressSmState()",
# "GetFawErrorStatistics()",
# "GetErrorCorrectionStatistics(channel,direction)",
# "GetPcsErrorStatistics(channel,direction)",
# "GetPcsTestPatternCheckerStatistics(channel,direction)",
# "GetOtuTestPatternCheckerStatistics(channel,direction)",
# "GetEstimatedPreCfecBer()",
# "GetFawErrorStatisticsOccurrenceInfo()",
# "GetPcsErrorStatisticsOccurrenceInfo(channel,direction)",
# "GetErrorCorrectionStatisticsOccurrenceInfo(channel,direction)",
# "GetIngressFifoInformation()",
# "GetEgressFifoInformation()",
# "GetFramerIngressFifoInformation(channel)",
# "GetFramerEgressFifoInformation(channel)",
# "SetEthernetMaxFrameLength(channel,direction,max_packet_length,max_broad_multi_length,max_jabber_length)",
# "GetEthernetMaxFrameLength(channel,direction)",
# "GetEthernetCounters(channel,direction)",
# "ReadEthernetPacketTrap(channel,direction,clean_memory)",
# "GetEthernetPacketTrapConfig(channel,direction)",
# "SetEthernetPacketTrapConfig(channel,direction,mac_source_address,mac_source_address_mask,mac_destination_address,mac_destination_address_mask,mac_ethertype,mac_ethertype_mask)",
# "SetEthernetBjAmConfig(channel,four_lane_pmd)",
# "GetEthernetBjAmConfig(channel)",
# "GetOtnOhpAlarms(channel,map_level)",
# "GetOtnAlarms(channel,direction)",
# "GetOtnGmpAlarms(channel)",
# "GetEthernetAlarms(channel,direction)",
# "GetFlexOAlarms(channel)",
# "GetFlexEAlarms(channel,direction)",
# "GetTemperature(sensor_id_0,sensor_id_1,sensor_id_2,sensor_id_3)",
# "ReadLinePowerSupply(lane)",
# "GetExtLrxCodes(lane)",
# "GetExtLrxLatency()",
# "GetExtLrxPrefs()",
# "GetExtLrxState()",
# "GetExtLrxStatus()",
# "SetExtLrxLatency(calibration_refresh_delay)",
# "SetExtLrxCalDelays(rest_delay,refresh_delay)",
# "GetExtLrxCalDelays()",
# "RunDiagnosticUnitCapture(signal_source)",
# "GetPllStatus(pll_select)",
# "GetDiagnosticUnitCaptureData()",
# "ReleaseDiagnosticUnit()",
# "GetLineOpticalChannelMonitorsAll()",
# "GetLineOpticalChannelMonitorsItem(item)",
# "SetOpticalMonitorsConfig(action,lut,arg_array)",
# "GetOpticalMonitorsConfig(action)",
# "GetOsnrCalibrationTable(row)",
# "GetLineOpticalChannelMonitorsOccurrenceInfo()",
# "GetOpticalMonitorAngle()",
# "ControlAvs(Ctrl,Vstep,CurrentV,AVSAnalysisMode,AVSRate,Prv,Reserved)",
# "ArmAvsBoost(persistence_time,enable)",
# "GetAvsBoostConfig()",
# "SetMonitorClocks(enable_ltx_monclk,reserved)",
# "GetMonitorClocks()"]


# # for test only ------begin
# @module_bp.route('/mod_dsp_new')
# def mod_dsp_new():
#     return render_template('mod_dsp_new.html', title='DSP API (canopus)',for_customer=for_customer)



# @module_bp.route('/api/suggest', methods=['POST'])
# def suggest():
#     print("suggest ...")
#     keyword = request.form["keyword"]
#     print("keyword:", keyword)

#     suggest_str = "<ul id='apis-list'>"
#     for item in apis_list:
#         if keyword != "*":
#             if keyword.lower() in item.lower():
#                 suggest_str += r"<li onClick=selectApiItem('{}')>{}</li>".format(item, item)
#         else:
#             suggest_str += r"<li onClick=selectApiItem('{}')>{}</li>".format(item, item)

#     suggest_str += "</ul>"
#     return suggest_str



# @module_bp.route('/api/set_mod_dsp_new_api_suggest', methods=['POST'])
# def set_mod_dsp_new_api_suggest():
#     print("set_mod_dsp_new_api_suggest ...")
#     b = Broker()
#     dsp = Canopus(b)
#     ca = CanopusApi(dsp)
#     # b.cdb_psw()

#     cmd = request.form["cmd"]
#     params_str = request.form["params_str"]
#     print(cmd)
#     print(params_str)

#     # ret = "OK"
#     try:
#         if params_str == "":
#             ret = eval("ca." + cmd + "()")
#         else:
#             print("with params, todo ...")
#             # params_str = params_str[1:].replace("#", ",")
#             ret = eval("ca." + cmd + "(" + params_str + ")")
#         return jsonify(ret)
#     except Exception as e:
#         return  str(e)

    


# @module_bp.route('/api/set_mod_dsp_new_api', methods=['POST'])
# def set_mod_dsp_new_api():
#     print("set_mod_dsp_new_api ...")
#     b = Broker()
#     dsp = Canopus(b)
#     ca = CanopusApi(dsp)
#     # b.cdb_psw()

#     cmd = request.form["cmd"]
#     params_str = request.form["params_str"]
#     print(cmd)
#     print(params_str)

#     ret = "OK"
#     if params_str == "":
#         ret = eval("ca." + cmd + "()")
#     else:
#         print("with params, todo ...")
#         params_str = params_str[1:].replace("#", ",")
#         ret = eval("ca." + cmd + "(" + params_str + ")")

#     return jsonify(ret)


# @module_bp.route('/mod_dsp_deneb')
# def mod_dsp_deneb():
#     return render_template('mod_dsp_deneb.html', title='DSP API (deneb)',for_customer=for_customer)

# @module_bp.route('/api/set_mod_dsp_deneb_api', methods=['POST'])
# def set_mod_dsp_deneb_api():
#     print("set_mod_dsp_deneb_api ...")
#     b = Broker()
#     dsp = Canopus(b)
#     ca = DenebApi(dsp)
#     b.cdb_psw()

#     cmd = request.form["cmd"]
#     params_str = request.form["params_str"]
#     print(cmd)
#     print(params_str)

#     ret = "OK"
#     if params_str == "":
#         ret = eval("ca." + cmd + "()")
#     else:
#         print("with params, todo ...")
#         params_str = params_str[1:].replace("#", ",")
#         ret = eval("ca." + cmd + "(" + params_str + ")")

#     return jsonify(ret)

# # for test only ------end


# @module_bp.route('/mod_dsp')
# def mod_dsp():
#     # file = open('./static/files/dsp_api.old.yaml', 'r', encoding="utf-8")
#     # file_data = file.read()
#     # file.close()
#     # dsp_yaml = yaml.load(file_data)
#     # return render_template('mod_dsp.html', title='DSP API Settings', dsp_yaml=dsp_yaml)
#     return render_template('mod_dsp.html', title='DSP API Settings',for_customer=for_customer)


# @module_bp.route('/api/btn_start_up')
# def btn_start_up():
#     b = Broker()
#     b.cdb_psw()
#     dsp = Canopus(b)
#     dsp.startup()
#     return "DSP startup command has been sent."


# @module_bp.route('/api/btn_get_state')
# def btn_get_state():
#     b = Broker()
#     dsp = Canopus(b)
#     return str(dsp.state())


# @module_bp.route('/api/btn_disable_TriggerMonitor')
# def btn_disable_TriggerMonitor():
#     b = Broker()
#     b.twi_bw(127,0xff)
#     b.twi_bw(163, 1)
#     return "TriggerMonitor has been disabled."


# @module_bp.route('/api/dsp_api', methods=['POST'])
# def dsp_api():
#     b = Broker()
#     set_api = request.form["opt"]
#     cmdword = request.form["cmdword"]
#     params_str = request.form["params_str"]
#     position_str = request.form["position_str"]
#     params_type_str = request.form["params_type_str"]
#     cmd = request.form["cmd"]
#     params_multiply_factor_str = request.form["params_multiply_factor_str"]
#     # return "OK"
#     # cmdword, params_str, position_str,
#     # params_type_str, cmd, params_multiply_factor_str

#     f = open('./static/files/dsp_api.yaml')
#     x = yaml.load(f)

#     response_string = ''
#     cmd_lst = []
#     for a in cmdword.split(","):
#         cmd_lst.append(int(a))

#     command = bytearray(cmd_lst)

#     if params_str == '':
#         pass
#     else:
#         params_str = params_str[0:-1:1]
#         params = params_str.split(",")
#         position_str = position_str[0:-1:1]
#         position = position_str.split("|")
#         params_type_str = params_type_str[0:-1:1]
#         params_type = params_type_str.split("|")
#         params_multiply_factor_str = params_multiply_factor_str[0:-1:1]
#         params_multiply_factor = params_multiply_factor_str.split("|")

#         param_val = 0
#         idx = 0

#         # pass paraments for API 'Read Registers (32-bits)' ------
#         begin = 0
#         end = 0
#         if cmd == 'Read Registers (32-bits)':
#             begin = int(params[1])
#             end = int(params[2])
#         # --------------------------------------------------------
#         while idx < len(params):
#             print("idx" + str(idx))
#             if 'Choice' == params_type[idx]:
#                 param_val = int(params[idx])
#             elif 'Number' == params_type[idx]:
#                 param_val = int(str(params[idx]).strip())
#             elif 'Hexadecimal' == params_type[idx]:
#                 param_val = int(str(params[idx]).strip(), 16)
#             elif 'Float' == params_type[idx]:
#                 # to do
#                 param_val = float(params[idx])
#                 if 1 != int(params_multiply_factor[idx]):
#                     param_val = round(param_val *
#                                       int(params_multiply_factor[idx]))

#             #print("params_type:" + params_type[idx] + "val: " + str(param_val))

#             #return str(position[idx])
#             position_lst = position[idx].split(",")

#             pos_lst = []
#             print("position_lst...")
#             for a in position_lst:
#                 pos_lst.append(int(a))
#             print(pos_lst)

#             if (pos_lst[2] == 0):
#                 pass
#             elif (pos_lst[2] < 8):
#                 byte_pos = pos_lst[0]
#                 bits_pos = pos_lst[1]

#                 bits_mask = 2**pos_lst[2] - 1
#                 command[byte_pos] &= ~(bits_mask << bits_pos)
#                 command[byte_pos] |= (param_val & bits_mask) << bits_pos
#             else:
#                 byte_pos = pos_lst[0]
#                 bytes_size = pos_lst[2] // 8
#                 pos_offset = 0
#                 while pos_offset < bytes_size:
#                     command[byte_pos + pos_offset] = (param_val >>
#                                                       (8 * pos_offset)) & 0xff
#                     pos_offset += 1
#             idx += 1
#             print("--------------------------")

#     # dsp = Dsp(b)
#     dsp = Canopus(b)
#     print(command)
#     resArray = dsp.api(command)
#     # return str(resArray)

#     response_string += str(resArray) + '\r\n'

#     response_string += '\r\n'
#     response_string += 'command:' + '\r\n'
#     response_string += str(command) + '\r\n'

#     rx = resArray
#     #verify status
#     if (rx[2] != 0x00):
#         info = "Status Code: " + "(%d) " % rx[2]
#         if 0x01 == rx[2]:
#             info += "NOT_COMPLETED"
#         elif 0x02 == rx[2]:
#             info += "INVALID"
#         elif 0x03 == rx[2]:
#             info += "INVALID_FIELD"
#         elif 0x04 == rx[2]:
#             info += "FAILED"
#         elif 0x05 == rx[2]:
#             info += "BUSY"
#         elif 0x06 == rx[2]:
#             info += "CANCELLED"
#         elif 0x07 == rx[2]:
#             info += "TIMEOUT"
#         elif 0x08 == rx[2]:
#             info += "HW_ERROR"
#         elif 0x0a == rx[2]:
#             info += "ERR_READING"
#         elif 0x0b == rx[2]:
#             info += "FAIL_CONVERGE"
#         elif 0x0c == rx[2]:
#             info += "HOST_RX_PLL_UNLOCK"
#         elif 0x0d == rx[2]:
#             info += "CLOCK_NO_CORRECTION"
#         elif 0x0f == rx[2]:
#             info += "AGC_FAIL"
#         elif 0x10 == rx[2]:
#             info += "WRONG_MODE"
#         else:
#             info += "UNKNOWN"
#         info += '\r\n'
#         #self.__output.AppendText(info)
#         response_string += info
#         print(response_string)
#         return response_string
#     else:
#         #print(x[0])
#         for a in x:
#             #print(a)
#             idx = 0
#             #if a.get(':cmd') == 'Get Line Ingress DSP Status':
#             if a.get(':cmd') == str(cmd):
#                 #if ':response-decode' in self.__config[':controls'][row]:
#                 if ':response-decode' in a:
#                     # print(self.__config[':controls'][row][':response-decode'])
#                     numerator = 0
#                     denominator = 0
#                     #self.__output.AppendText("Deciphering:\r\n")
#                     response_string += "Deciphering:\r\n"

#                     idx = 0
#                     while idx < len(a[':response-decode']):
#                         name = a[':response-decode'][idx][':name']
#                         description = a[':response-decode'][idx][
#                             ':description']
#                         position = a[':response-decode'][idx][':position']
#                         bytes_pos = position[0]
#                         bits_start = position[1]
#                         bits_siz = position[2]
#                         # print(bytes_pos, bits_start, bits_siz)
#                         if bits_siz < 8:
#                             val = rx[bytes_pos]
#                             val = (
#                                 val &
#                                 (2**bits_siz - 1) << bits_start) >> bits_start
#                         else:
#                             bytes_siz = bits_siz // 8
#                             pos_offset = 0
#                             val = 0
#                             while pos_offset < bytes_siz:
#                                 val += rx[bytes_pos +
#                                           pos_offset] << (8 * pos_offset)
#                                 pos_offset += 1
#                         if 'numerator' == a[':response-decode'][idx][
#                                 ':description']:
#                             numerator = val
#                         elif 'denominator' == a[':response-decode'][idx][
#                                 ':description']:
#                             denominator = val

#                         if 'B' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('B',
#                                                 rx[bytes_pos:bytes_pos + 1])[0]
#                             response_string += "  %s decode value:\t%d\r\n" % (
#                                 name, val)

#                         if '<I' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('<I',
#                                                 rx[bytes_pos:bytes_pos + 4])[0]
#                             response_string += "  %s decode value:\t%d\r\n" % (
#                                 name, val)

#                         if '<H' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('<H',
#                                                 rx[bytes_pos:bytes_pos + 2])[0]
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '<H_2**15' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack(
#                                 '<H', rx[bytes_pos:bytes_pos + 2])[0] / (2**15)
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '<H_2**17' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack(
#                                 '<H', rx[bytes_pos:bytes_pos + 2])[0] / (2**17)
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '<H_log10_2**11' == a[':response-decode'][idx][
#                                 ':type']:
#                             val = 10 * math.log10(
#                                 struct.unpack('<H', rx[bytes_pos:bytes_pos +
#                                                        2])[0] / (2**11))
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '<h' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('<h',
#                                                 rx[bytes_pos:bytes_pos + 2])[0]
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '<h_64*3' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('<h', rx[bytes_pos:bytes_pos +
#                                                          2])[0] / (64 * 3)
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '60b' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('60b', rx[bytes_pos:bytes_pos +
#                                                           60])[0]
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if '<Q' == a[':response-decode'][idx][':type']:
#                             val = struct.unpack('<Q',
#                                                 rx[bytes_pos:bytes_pos + 8])[0]
#                             response_string += "  %s decode value:\t%s\r\n" % (
#                                 name, str(val))

#                         if 'signed short' == a[':response-decode'][idx][
#                                 ':type']:
#                             if val > (1 <<
#                                       (bits_siz - 1)):  # judge minus value
#                                 val = ((1 << bits_siz) -
#                                        val) * -1  #translate to minus
#                         if ':fixed_point_notaion' in a[':response-decode'][
#                                 idx]:
#                             if 'true' == a[':response-decode'][idx][
#                                     ':fixed_point_notaion']:
#                                 total_bits = a[':response-decode'][idx][
#                                     ':total_bits']
#                                 fractional_bits = a[':response-decode'][idx][
#                                     ':fractional_bits']
#                                 if 'true' == a[':response-decode'][idx][
#                                         ':signed']:  #signed
#                                     if val & (1 <<
#                                               (total_bits - 1)):  #negative
#                                         decode_val = (val - 2**total_bits) / (
#                                             2**fractional_bits)
#                                     else:  #positve
#                                         decode_val = val / (2**fractional_bits)
#                                 else:  #unsigned
#                                     decode_val = val / (2**fractional_bits)
#                                 #self.__output.AppendText("  %s decode value:\t%f\n" % (name, decode_val))
#                                 response_string += "  %s decode value:\t%f\r\n" % (
#                                     name, decode_val)

#                         if ':eval' in a[':response-decode'][idx]:
#                             try:
#                                 val = eval(a[':response-decode'][idx]
#                                            [':eval'].format(val))
#                                 formatstr = "  %s:\t" + a[':response-decode'][
#                                     idx][':display_holder'] + "\r\n"
#                                 kv_str = (formatstr % (name, val))
#                                 #self.__output.AppendText(formatstr % (name, val))
#                                 response_string += kv_str
#                             except ValueError:
#                                 #self.__output.AppendText("  %s:\t%d\r\n" % (name, val))
#                                 kv_str = ("  %s:\t%d\r\n" % (name, val))
#                                 response_string += kv_str
#                         else:
#                             #self.__output.AppendText("  %s:\t%d\r\n" % (name, val))
#                             kv_str = ("  %s:\t%d\r\n" % (name, val))
#                             response_string += kv_str
#                             if ':cal' in a[':response-decode'][idx]:
#                                 if denominator == 0:
#                                     Ber = numerator
#                                 else:
#                                     Ber = numerator / denominator
#                                 s = "%E" % Ber  #translate to scientific notation
#                                 #self.__output.AppendText("  %s:\t%s\r\n" % ('BER', s))
#                                 kv_str = ("  %s:\t%s\r\n" % ('BER', s))
#                                 response_string += kv_str
#                                 numerator = 0
#                                 denominator = 0

#                         if ':field_decode' in a[':response-decode'][idx]:
#                             if a[':response-decode'][idx][':field_decode']:
#                                 # #begin, end = self.GetFieldDefinition(row)
#                                 # begin = 0
#                                 # end = 8

#                                 val = val >> begin
#                                 val &= 2**(end - begin + 1) - 1
#                                 #self.__output.AppendText("  Field Value:\t[%d, %d] 0x%03x\r\n" % (begin, end, val))
#                                 kv_str = (
#                                     "  Field Value:\t[%d, %d] 0x%03x\r\n" %
#                                     (begin, end, val))
#                                 response_string += kv_str
#                                 pass
#                         idx += 1
#                 else:
#                     pass

#             #break

#     #print(response_string)
#     return response_string


# # ---------------------------------------------------------------------------------------------


# @module_bp.route('/api/GetFawErrorStatistics', methods=['POST'])
# def GetFawErrorStatistics():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         return str(dsp.get_faw_error_statistics())
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/GetCoreCfecTestPatternCheckerCounters',
#                  methods=['POST'])
# def GetCoreCfecTestPatternCheckerCounters():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         return str(dsp.get_core_cfec_test_pattern_checker_counters())
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetCoreCfecTestPatternGeneratorConfig',
#                  methods=['POST'])
# def SetCoreCfecTestPatternGeneratorConfig():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetCoreCfecTestPatternGeneratorConfig(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetCoreCfecTestPatternCheckerConfig', methods=['POST'])
# def SetCoreCfecTestPatternCheckerConfig():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetCoreCfecTestPatternCheckerConfig(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/ReStartLineIngressDsp', methods=['POST'])
# def ReStartLineIngressDsp():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         return str(dsp.ReStartLineIngressDsp(int(p1)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/get_ism_status', methods=['POST'])
# def get_ism_status():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         return str(dsp.get_ism_status())
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetPcsTestPatternGeneratorConfig', methods=['POST'])
# def SetPcsTestPatternGeneratorConfig():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         p3 = request.form["p3"]
#         p4 = request.form["p4"]
#         return str(
#             dsp.SetPcsTestPatternGeneratorConfig(int(p1), int(p2), int(p3),
#                                                  int(p4)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetPcsTestPatternCheckerConfig', methods=['POST'])
# def SetPcsTestPatternCheckerConfig():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         p3 = request.form["p3"]
#         p4 = request.form["p4"]
#         return str(
#             dsp.SetPcsTestPatternCheckerConfig(int(p1), int(p2), int(p3),
#                                                int(p4)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/GetPcsTestPatternCheckerStatistics', methods=['POST'])
# def GetPcsTestPatternCheckerStatistics():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(
#             dsp.get_pcs_test_pattern_checker_statistics(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetLineEgressLaneMute', methods=['POST'])
# def SetLineEgressLaneMute():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetLineEgressLaneMute(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetHostIngressLaneMute', methods=['POST'])
# def SetHostIngressLaneMute():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetHostIngressLaneMute(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/GetLineEgressLowSrFilterCoefficients', methods=['POST'])
# def GetLineEgressLowSrFilterCoefficients():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         return str(dsp.GetLineEgressLowSrFilterCoefficients(int(p1)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetLineEgressLowSrFilterCoefficients', methods=['POST'])
# def SetLineEgressLowSrFilterCoefficients():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         coefs = []
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         p_tmp = p2.split(',')
#         for i in p_tmp:
#             coefs.append(int(i))
#         return str(dsp.SetLineEgressLowSrFilterCoefficients(int(p1), coefs))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetLineEgressLowSrLaneAttenuation', methods=['POST'])
# def SetLineEgressLowSrLaneAttenuation():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetLineEgressLowSrLaneAttenuation(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/GetLineEgressLowSrLaneAttenuation', methods=['POST'])
# def GetLineEgressLowSrLaneAttenuation():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         return str(dsp.get_line_egress_low_sr_lane_attenuation(int(p1)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetLineEgressLowSrLaneSkew', methods=['POST'])
# def SetLineEgressLowSrLaneSkew():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetLineEgressLowSrLaneSkew(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/GetLineEgressLowSrLaneSkew', methods=['POST'])
# def GetLineEgressLowSrLaneSkew():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         return str(dsp.GetLineEgressLowSrLaneSkew(int(p1)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetLineIngressSkew', methods=['POST'])
# def SetLineIngressSkew():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetLineIngressSkew(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/get_line_ingress_skew', methods=['POST'])
# def get_line_ingress_skew():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         return str(dsp.get_line_ingress_skew(int(p1)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/SetLineEgressHighSrLaneSkew', methods=['POST'])
# def SetLineEgressHighSrLaneSkew():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         p2 = request.form["p2"]
#         return str(dsp.SetLineEgressHighSrLaneSkew(int(p1), int(p2)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/get_line_egress_high_sr_lane_skew', methods=['POST'])
# def get_line_egress_high_sr_lane_skew():
#     try:
#         b = Broker()
#         dsp = Canopus(b)
#         p1 = request.form["p1"]
#         return str(dsp.get_line_egress_high_sr_lane_skew(int(p1)))
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/read_firmware_information', methods=['POST'])
# def read_firmware_information():
#     try:
#         b = Broker()
#         b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#         dsp = Canopus(b)
#         return str(dsp.read_firmware_information())
#     except BaseException as e:
#         return str(e)


# @module_bp.route('/api/GetCoreCfecTestPatternCheckerStatistics', methods=['POST'])
# def GetCoreCfecTestPatternCheckerStatistics():
#     b = Broker()
#     dsp = Canopus(b)
#     ca = CanopusApi(dsp)
#     return str(ca.GetCoreCfecTestPatternCheckerStatistics())


# @module_bp.route('/api/GetEstimatedPreCfecBer', methods=['POST'])
# def GetEstimatedPreCfecBer():
#     b = Broker()
#     dsp = Canopus(b)
#     ca = CanopusApi(dsp)
#     # return str(ca.GetEstimatedPreCfecBer())
#     CFEC_BER = ca.GetEstimatedPreCfecBer()
#     if CFEC_BER['staircaise_estimated_ber_order_of_magnitude'] != 0:
#         A = CFEC_BER['staircaise_estimated_ber_order_of_magnitude'] - 65536
#     else:
#         A = 0
#     if CFEC_BER['hamming_estimated_ber_order_of_magnitude'] != 0:
#         B = CFEC_BER['hamming_estimated_ber_order_of_magnitude'] - 65536
#     else:
#         B = 0
#     Pre_FEC_BER = float(CFEC_BER['staircaise_estimated_ber_mantissa'])/4096*pow(10,A)+float(CFEC_BER['hamming_estimated_ber_mantissa'])/4096*pow(10,B) 

#     return str(ca.GetEstimatedPreCfecBer()) + "\r\n Pre_FEC_BER：" + str(Pre_FEC_BER)


# ##################################################
# # MOD VOA SCAN
# ##################################################
# @module_bp.route('/mod_voa')
# def mod_voa():
#     return render_template('mod_voa.html', title='VOA Scan',for_customer=for_customer)


# @module_bp.route('/api/get_voa_scan_data', methods=['GET', 'POST'])
# def get_voa_scan_data():
#     # scan_period = 10
#     # start_v = 0.0
#     # stop_v = 4.5
#     # step_v = 0.01
#     title_flag = True
#     direction = str(request.form["direction"])
#     voa_x_y = str(request.form["voa_x_y"])
#     scan_period = int(request.form["scan_period"])
#     start_v = float(request.form["start_v"])
#     stop_v = float(request.form["stop_v"])
#     step_v = float(request.form["step_v"])

#     print('--------------------------------------')
#     print(direction)
#     print(scan_period)
#     print(start_v)
#     print(stop_v)
#     print(step_v)
#     print('--------------------------------------')

#     data, data_chart = [], []

#     row0, row1, row2, row3, row4 = [], [], [], [], []

#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     while True:
#         if start_v < stop_v:

#             if direction == 'tx':

#                 if voa_x_y == 'voa_x':
#                     if title_flag:
#                         row0 = ['MCU1_TX_VOA_X']
#                         title_flag = False

#                     # MCU1_TX_VOA_X
#                     a = Aout(b, 'MCU1_TX_VOA_X')
#                     a.aval = float(start_v)
#                     row1.append(round(float(start_v), 2))

#                     a = Ain(b, 'POST_MPDX_DC_MCU2ADC')
#                     # cells_val = str(a.dval) + ',' + str(round(a.aval,2))
#                     row2.append(round(a.aval, 2))

#                     start_v = start_v + step_v
#                     time.sleep(scan_period / 1000)
#                 else:
#                     if title_flag:
#                         row0 = ['MCU1_TX_VOA_Y']
#                         title_flag = False

#                     # MCU1_TX_VOA_Y
#                     a = Aout(b, 'MCU1_TX_VOA_Y')
#                     a.aval = float(start_v)
#                     row1.append(round(float(start_v), 2))

#                     a = Ain(b, 'POST_MPDY_DC_MCU2ADC')
#                     # cells_val = str(a.dval) + ',' + str(round(a.aval,2))
#                     row2.append(round(a.aval, 2))

#                     start_v = start_v + step_v
#                     time.sleep(scan_period / 1000)
#             else:  #rx
#                 if voa_x_y == 'voa_x':
#                     if title_flag:
#                         row0 = ['DAC_RX_VOA_X']
#                         title_flag = False

#                     # DAC_RX_VOA_X
#                     a = Aout(b, 'DAC_RX_VOA_X')
#                     a.aval = float(start_v)
#                     row1.append(round(float(start_v), 2))

#                     a = Ain(b, 'RX_MPD_X_MCU1')
#                     # cells_val = str(a.dval) + ',' + str(round(a.aval,2))
#                     row2.append(round(a.aval, 2))

#                     start_v = start_v + step_v
#                     time.sleep(scan_period / 1000)
#                 else:
#                     if title_flag:
#                         row0 = ['DAC_RX_VOA_Y']
#                         title_flag = False

#                     # DAC_RX_VOA_Y
#                     a = Aout(b, 'DAC_RX_VOA_Y')
#                     a.aval = float(start_v)
#                     row1.append(round(float(start_v), 2))

#                     a = Ain(b, 'RX_MPD_Y_MCU1')
#                     # cells_val = str(a.dval) + ',' + str(round(a.aval,2))
#                     row2.append(round(a.aval, 2))

#                     start_v = start_v + step_v
#                     time.sleep(scan_period / 1000)
#         else:
#             break

#     data = [row0, row1, row2]
#     data_chart = [row1, row2]

#     path = './static/files/voa.csv'
#     with open(path, 'w', encoding='utf-8', newline='') as f:
#         writer = csv.writer(f, dialect='excel')
#         for row in data:
#             writer.writerow(row)

#     # print(data)
#     return str(data_chart)


# # @module_bp.route('/api/dl_voa_data', methods=['GET', 'POST'])
# # def dl_voa_data():
# #     print("---------------------------")
# #     print("/api/dl_voa_data")
# #     path = './templates/files/voa111.csv'
# #     return send_file(path, as_attachment=True)


# @module_bp.route('/api/btn_get_cmis_info')
# def btn_get_cmis_info():
#     try:
#         print('btn_get_cmis_info....')

#         # read cmis xls file to map #########################################################
#         if os.path.exists("./templates/files/cmis.xlsx"):
#             has_cmis_file = True
#         else:
#             has_cmis_file = False

#         cmis_map = {}
#         page_map = {
#             '1': 'Low',
#             '3': '00',
#             '4': '01',
#             '5': '02',
#             '6': '04',
#             '7': '10',
#             '8': '11',
#             '9': '12',
#             '10': '13',
#             '11': '14'
#         }

#         for col in [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]:
#             pdata = pd.read_excel("./templates/files/cmis.xlsx",
#                                   sheet_name="Summary",
#                                   usecols=[col])
#             pdata = pdata.dropna(how='any')
#             #print(data)
#             if col == 1:
#                 start_addr = 0
#             else:
#                 start_addr = 128

#             for index, row in pdata.iterrows():
#                 if index > 0:
#                     cmis_map.update(
#                         {page_map[str(col)] + '_' + str(start_addr): row[0]})
#                     start_addr = start_addr + 1

#         print(cmis_map)

#         # pages = ['Low', '00', '01', '02', '04', '10', '11', '12', '13', '14', '2F', '41', '42', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff', 'ff']
#         # pages = ['Low', '00', '01', '02', '04', '10', '11', '12', '13', '14', '2F', '41', '42']
#         # pages = ['Low', '00', '01', '02']
#         # page low, 0 ,1,2,4, 10h,,11h,12h,13h,14h
#         pages = ['Low', '00', '01', '02', '04', '10', '11', '12', '13', '14']

#         addr1 = []
#         for x in range(0, 128):
#             addr1.append(x)

#         addr2 = []
#         for x in range(128, 256):
#             addr2.append(x)

#         # output format2
#         # Page      Address               Data(in dec)       Data(in hex)       Data (in ASCII)
#         # 0              3              3              03           NA
#         # 0              4              0              00           NA

#         path1 = './static/files/cmis_info1.csv'
#         path2 = './static/files/cmis_info2.csv'

#         with open(path1, 'w') as f1:
#             f1.write(
#                 'Page,Address,Data(read from module), Data(read from cmis.xlsx)\n'
#             )
#             with open(path2, 'w') as f2:
#                 # f2.write('{:<15} {:<15} {:<15} {:<15} {:<15}\n'. format('Page', 'Address', 'Data(dec)', 'Data(hex)', 'Data(ASCII)'))
#                 # f2.write('{:<15} {:<15} {:<15} {:<15} {:<15}\n'. format('-'*15, '-'*15, '-'*15, '-'*15, '-'*15))
#                 f2.write('Page,Address,Data(dec),Data(hex),Data(ASCII)\n')
#                 for p in pages:
#                     if p == 'Low':
#                         address = addr1
#                         page = 'Low'
#                     else:
#                         address = addr2
#                         page = p
#                         #switch page!
#                         a.set_twi(1, 127, '0x' + str(p))

#                     # f.write('page: {}\n'.format(page))
#                     for addr in address:
#                         ret = a.get_twi(1, addr)
#                         ret1 = ret[:-1]

#                         ret_hex = ret1
#                         ret_dec = int('0x' + str(ret1), 16)
#                         # only show char (dec val 33~126) else show NA
#                         if ret_dec < 33 or ret_dec > 126:
#                             ret_ascii = 'NA'
#                         else:
#                             ret_ascii = chr(int('0x' + str(ret1), 16))

#                         print('page: {} -> addr: {} -> val: {}\n'.format(
#                             page, addr, ret_hex))

#                         val1 = int(
#                             '0x' + str(cmis_map[str(page) + '_' + str(addr)]),
#                             16)
#                         # compare! register value and excel file
#                         if val1 == ret_dec:
#                             # f.write('addr: {} -> val: {}\n'.format(addr, ret_hex))
#                             f1.write('{},{},{}\n'.format(page, addr, ret_hex))
#                         else:
#                             # f.write('addr: {} -> val: {} ####> {}\n'.format(addr, ret_hex, cmis_map[ str(page) + '_' + str(addr)]))
#                             f1.write('{},{},{},{}\n'.format(
#                                 page, addr, ret_hex,
#                                 cmis_map[str(page) + '_' + str(addr)]))

#                         # f2.write('{:<15} {:<15} {:<15} {:<15} {:<15}\n'.format('low', addr, int('0x'+str(ret_hex), 16), ret1, 'NA'))
#                         f2.write('{},{},{},{},{}\n'.format(
#                             page, addr, ret_dec, ret_hex, ret_ascii))
#                         time.sleep(0.008)

#         f2.close()
#         f1.close()
#         return ('ok')
#     except:
#         return ('Please download cmis default table firstly and try again.')


# @module_bp.route('/api/compare_mod_config_table')
# def compare_mod_config_table():
#     print('compare_mod_config_table....')
#     module_config_file = a.read_item_from_config_ini('dev',
#                                                      'module_config_file')
#     if module_config_file == "---":
#         return "no_file"
#     else:
#         print("Compare with: {}".format(module_config_file))
#         # compare ...

#         b = Broker()
#         b.cdb_psw()
#         flash = Flash(b)

#         # params_file = sys.argv[1]
#         params_file = './templates/files/' + module_config_file

#         wb = load_workbook(filename=params_file, data_only=True)

#         ver_byte_arr = b''
#         ver_sheet = wb['Sheet1']
#         ver_byte_arr += struct.pack('B',
#                                     int(ver_sheet['I2'].value))  #little endian
#         ver_byte_arr += struct.pack('B', int(ver_sheet['H2'].value))

#         # DSP sheet Start
#         dsp_sheet = wb['DSP']

#         dsp_byte_arr = b''
#         for i in dsp_sheet['E']:
#             if (None != i.value) and ('Target Value' != i.value):
#                 dsp_byte_arr += struct.pack('<i', int(i.value))
#                 # print(i.value)

#         # print(dsp_byte_arr)

#         print('dsp2_byte_arr ...')
#         dsp2_byte_arr = b''
#         try:
#             dsp2_sheet = wb['DSP2']
#             for i in dsp2_sheet['E']:
#                 if(None != i.value) and ('Target Value' != i.value):
#                     dsp2_byte_arr += struct.pack('<i', int(i.value))
#                     # print(i.value)
#         except:
#             print('Skip DSP2 Sheet...')

#         dac_byte_arr = b''
#         dac_sheet = wb['DAC']
#         for i in dac_sheet['E']:
#             if (None != i.value) and ('Translate Val' != i.value):
#                 # print(i.value)
#                 dac_byte_arr += struct.pack('<I', int(i.value))
#                 # print(i.value)
#         # print(dac_byte_arr)

#         ddm_byte_arr = b''
#         ddm_sheet = wb['DDM']
#         for i in ddm_sheet['C']:
#             if (None != i.value) and ('Target Value' != i.value):
#                 ddm_byte_arr += struct.pack('<f', float(i.value))
#         # print(ddm_byte_arr)

#         ctrl_byte_arr = b''
#         try:
#             ctrl_sheet = wb['CTRL']
#             for i in ctrl_sheet['C']:
#                 if (None != i.value) and ('En/Dis' != i.value):
#                     # print(i.value)
#                     ctrl_byte_arr += struct.pack('<i', int(i.value))
#             print('ctrl_byte_arr')
#             print(ctrl_byte_arr)
#         except KeyError:
#             print("No CTRL sheet, skip ...")

#         biaskb_byte_arr = b''
#         try:
#             biaskb_sheet = wb['BiasKB']
#             for i in biaskb_sheet['C']:
#                 if(None != i.value):
#                     # print(i.value)
#                     biaskb_byte_arr += struct.pack('<f', float(i.value))
#             print('biaskb_byte_arr')
#             print(biaskb_byte_arr)
#         except KeyError:
#             print("No BiasKB sheet, skip ...")

#         abc_byte_arr = b''
#         try:
#             abc_sheet = wb['ABC']
            
#             for row in abc_sheet.iter_rows():
#                 if row[1].value is None or row[2].value is None:
#                     continue
#                 else:
#                     print(row[1].value,'<---->',row[2].value)
#                     abc_byte_arr += struct.pack( row[1].value, row[2].value)
                
#             print('abc_byte_arr')
#             print(abc_byte_arr)
#         except:
#             print('Skip ABC Sheet...')    

#         data = dsp_byte_arr + dsp2_byte_arr + dac_byte_arr + ddm_byte_arr + ctrl_byte_arr + biaskb_byte_arr + abc_byte_arr
#         # print(data)
#         crcVal = crc.main(data)
#         length = len(data)
#         reserved = ''.join('{:0106X}'.format(0))  #fill 55 bytes 0
#         data = b'\x10' + \
#                struct.pack('<I', length) + \
#                struct.pack('<I', crcVal) + \
#                ver_byte_arr + \
#                bytearray.fromhex(reserved) + \
#                dsp_byte_arr + \
#                dsp2_byte_arr + \
#                dac_byte_arr + \
#                ddm_byte_arr + \
#                ctrl_byte_arr + \
#                biaskb_byte_arr + \
#                abc_byte_arr

#         # print(data)

#         startAddr = 0x300000
#         sectorNo = int(startAddr / 4096)

#         readRes = b''
#         remaining = len(data)
#         readout = 0
#         BLOCK_SIZE = 128
#         while remaining:
#             if remaining >= BLOCK_SIZE:
#                 res = flash.read(startAddr + readout, BLOCK_SIZE)
#                 readRes += struct.pack('%sB' % len(res), *res)
#                 readout += BLOCK_SIZE
#                 remaining -= BLOCK_SIZE
#             else:
#                 res = flash.read(startAddr + readout, remaining)
#                 readRes += struct.pack('%sB' % len(res), *res)
#                 readout += remaining
#                 remaining -= remaining
#         # print(readRes)

#         #module's table ver
#         # print('Table ver: %d.%d\n' % (struct.unpack('B',readRes[10])[0], struct.unpack('B',readRes[9])[0]))
#         print('Table ver: %d.%d\n' % (readRes[10], readRes[9]))
#         offset = 64
#         # DSP sheet Start
#         dsp_sheet = wb['DSP']
#         for i in dsp_sheet['E']:
#             if (None != i.value) and ('Target Value' != i.value):
#                 print(
#                     str(dsp_sheet.cell(i.row, 2).value) + ': %d\n' %
#                     struct.unpack('<i', readRes[offset:offset + 4])[0])
#                 offset += 4

#         try:
#             dsp2_sheet = wb['DSP']
#             for i in dsp2_sheet['E']:
#                 if (None != i.value) and ('Target Value' != i.value):
#                     print(
#                         str(dsp2_sheet.cell(i.row, 2).value) + ': %d\n' %
#                         struct.unpack('<i', readRes[offset:offset + 4])[0])
#                     offset += 4
#         except KeyError:
#             print("No DSP2 sheet, skip ....")

#         dac_sheet = wb['DAC']
#         for i in dac_sheet['E']:
#             if (None != i.value) and ('Translate Val' != i.value):
#                 print(
#                     dac_sheet.cell(i.row, 1).value + ': %d\n' %
#                     struct.unpack('<I', readRes[offset:offset + 4])[0])
#                 offset += 4

#         ddm_sheet = wb['DDM']
#         for i in ddm_sheet['C']:
#             if (None != i.value) and ('Target Value' != i.value):
#                 print(
#                     ddm_sheet.cell(i.row, 1).value + ': %f\n' %
#                     struct.unpack('<f', readRes[offset:offset + 4])[0])
#                 offset += 4

#         try:
#             ctrl_sheet = wb['CTRL']
#             for i in ctrl_sheet['C']:
#                 if (None != i.value) and ('En/Dis' != i.value):
#                     print(
#                         ctrl_sheet.cell(i.row, 1).value + ': %d\n' %
#                         struct.unpack('<I', readRes[offset:offset + 4])[0])
#                     offset += 4
#         except KeyError:
#             print("No CTRL sheet, skip ....")

#         try:
#             biaskb_sheet = wb['BiasKB']
#             for i in biaskb_sheet['C']:
#                 if(None != i.value) and ('Target Value' != i.value):
#                     print(biaskb_sheet.cell(i.row, 1).value + ': %f\n' % struct.unpack('<f', readRes[offset : offset+4])[0])
#                     offset += 4
#         except KeyError:
#             print("No BiasKB sheet, skip ....")


#         # abc_byte_arr = b''

#         abc_sheet = wb['ABC']
#         for row in abc_sheet.iter_rows():
#             if row[1].value is None or row[2].value is None:
#                 continue
#             else:
#                 # print(row[1].value,'<---->',row[2].value)
#                 # abc_byte_arr += struct.pack( row[1].value, row[2].value)
#                 print(row[0].value , ": ", struct.unpack(row[1].value, readRes[offset : offset+4])[0], '\n')
#                 offset +=  4



#         if readRes[1:] == data[1:]:
#             print("verfiy success\r\n")
#             return "Verify successfully."
#         else:
#             print("verfiy failed\r\n")
#             return "Verfiy failed."


# ##################################################
# # ABC Settings
# ##################################################
# @module_bp.route('/api/btn_abc_pid_get', methods=['POST'])
# def btn_abc_pid_get():
#     idx = request.form["idx"]
#     b = Broker()
#     abc = ABC(b)

#     L = []
#     for item in abc.pid_get(int(idx)):
#         L.append(item)

#     L.append(abc.polarity_get(int(idx)))
#     L.append(abc.step_get(int(idx)))
#     L.append(abc.method_get(int(idx)))
#     L.append(abc.target_get(int(idx)))
#     L.append(abc.theta_get(int(idx)))
#     return str(L).replace('[', '').replace(']', '')


# @module_bp.route('/api/btn_abc_pid_set', methods=['POST'])
# def btn_abc_pid_set():
#     idx = request.form["idx"]
#     abc_p_val = request.form["abc_p_val"]
#     abc_i_val = request.form["abc_i_val"]
#     abc_d_val = request.form["abc_d_val"]
#     abc_i_min_val = request.form["abc_i_min_val"]
#     abc_i_max_val = request.form["abc_i_max_val"]
#     abc_polarity_val = request.form["abc_polarity_val"]
#     abc_step_val = request.form["abc_step_val"]
#     abc_method_val = request.form["abc_method_val"]
#     abc_target_val = request.form["abc_target_val"]
#     abc_theta_val = request.form["abc_theta_val"]

#     b = Broker()
#     abc = ABC(b)
#     abc.pid_set(int(idx),
#                 (float(abc_p_val), float(abc_i_val), float(abc_d_val),
#                  float(abc_i_min_val), float(abc_i_max_val)))
#     #set polarity
#     abc.polarity_set(int(idx), int(abc_polarity_val))
#     #set step
#     abc.step_set(int(idx), float(abc_step_val))
#     #set method
#     abc.method_set(int(idx), int(abc_method_val))
#     #set target
#     abc.target_set(int(idx), float(abc_target_val))
#     #set theta
#     abc.theta_set(int(idx), int(abc_theta_val))
#     return "set_abc_pid ok"


# @module_bp.route('/api/set_abc_service', methods=['POST'])
# def set_abc_service():
#     abc_service_val = request.form["abc_service_val"]
#     b = Broker()
#     abc = ABC(b)
#     abc.service = int(abc_service_val, 16)
#     return "set_abc_service ok"


# @module_bp.route('/api/get_abc_service')
# def get_abc_service():
#     b = Broker()
#     abc = ABC(b)
#     return str(hex(abc.service))


# @module_bp.route('/api/set_abc_algo', methods=['POST'])
# def set_abc_algo():
#     abc_algo_val = request.form["abc_algo_val"]
#     b = Broker()
#     abc = ABC(b)
#     abc.algo = int(abc_algo_val)
#     return "set_abc_algo ok"


# @module_bp.route('/api/get_abc_algo')
# def get_abc_algo():
#     b = Broker()
#     abc = ABC(b)
#     return str(abc.algo)


# @module_bp.route('/api/set_abc_dither', methods=['POST'])
# def set_abc_dither():
#     abc_dither_val = request.form["abc_dither_val"]
#     b = Broker()
#     abc = ABC(b)
#     abc.dither = int(abc_dither_val)
#     return "set_abc_dither ok"


# @module_bp.route('/api/get_abc_dither')
# def get_abc_dither():
#     b = Broker()
#     abc = ABC(b)
#     return str(abc.dither)


# @module_bp.route('/api/set_abc_settings', methods=['POST'])
# def set_abc_settings():
#     abc_freq_idx_val = request.form["abc_freq_idx_val"]
#     abc_ampl_val = request.form["abc_ampl_val"]
#     abc_theta_val = request.form["abc_theta_val"]
#     abc_iter_val = request.form["abc_iter_val"]
#     b = Broker()
#     abc = ABC(b)
#     abc.setting = int(abc_freq_idx_val), int(abc_ampl_val), int(
#         abc_theta_val), int(abc_iter_val)
#     return "set_abc_setting ok"


# @module_bp.route('/api/get_abc_settings')
# def get_abc_settings():
#     b = Broker()
#     abc = ABC(b)
#     return str(abc.setting).replace('(', '').replace(')', '')


# @module_bp.route('/api/set_abc_fine', methods=['POST'])
# def set_abc_fine():
#     fine_val = request.form["fine_val"]
#     b = Broker()
#     abc = ABC(b)
#     abc.fine = int(fine_val)
#     return "set_abc_fine ok"


# @module_bp.route('/api/get_abc_fine')
# def get_abc_fine():
#     b = Broker()
#     abc = ABC(b)
#     return str(abc.fine)


# ##################################################
# # MOD DDM
# ##################################################
# @module_bp.route('/mod_ddm')
# def mod_ddm():
#     return render_template('mod_ddm.html', title='Module DDM',for_customer=for_customer)


# @module_bp.route('/api/get_ddm_values')
# def get_ddm_values():
#     b = Broker()

#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     # COSA Temperatureï¼?COSA_TEMP_OUT
#     # PCBA Temperature ï¼šPCB_TEMP_ADC
#     a = Ain(b, 'COSA_TEMP_OUT')
#     cosa_temp = a.aval
#     a = Ain(b, 'PCB_TEMP_ADC')
#     pcba_temp = a.aval


#     d = DDM(b)
#     ddt = d.dsp_die_temp
#     return (str( round(d.tx_power, 2) ) + ',' + str( round(d.rx_power, 2) ) + ',' +
#             str(round(d.vcc, 2)) + ',' + str(round(cosa_temp, 2)) + ',' +
#             str(round(pcba_temp, 2)) + ',' + str(round(d.case_temp, 2)) + ',' +
#             str(round(d.laser_temp, 2)) + ',' + str(round(d.dsp_temp, 2)) +
#             ',' + str(round(ddt[0], 2)) + ',' + str(round(ddt[1], 2)) + ',' +
#             str(round(ddt[2], 2)) + ',' + str(round(ddt[3], 2)))
#     # return ('0.00,0.00,0.00, str(round(cosa_temp, 2)), str(round(pcba_temp, 2)), 0.00,0.00,0.00,0.00,0.00,0.00,0.00')


# # @module_bp.route('/api/set_tx_power', methods=['GET', 'POST'])
# # def set_tx_power():
# #     b = Broker()
# #     d = DDM(b)
# #     # tx_power_val = request.form["tx_power_val"]
# #     # d.tx_power = float(tx_power_val)
# #     return "btn_set_tx_power ok"


# # constelattion diagram ##############################################################
# def demo_capture():
#     time.sleep(0.1)
#     y = []
#     for i in range(1, 11):
#         y.append(random.randint(10, 50))

#     x = np.arange(10)
#     fig = plt.figure()
#     ax = plt.subplot(111)
#     ax.plot(x, y, label='$y = numbers')
#     plt.title('Legend inside')
#     ax.legend()
#     # plt.show()
#     tt = str(time.time())
#     # ./static/files/voa.csv
#     fig.savefig('./static/files/plot' + tt + '.png')

#     # fig.savefig('../php/plot.png')
#     plt.close('all')
#     # time.sleep(1)
#     return 'files/plot' + tt + '.png'


# def get_float_from_fixed_point(fixed_point_number, n_bits, n_fixed, is_signed):
#     sign = True
#     if is_signed:
#         if (fixed_point_number >> (n_bits - 1)) & 0x1:
#             fixed_point_number ^= 0xFFFFFFFFFFFFFFFF
#             fixed_point_number += 1
#             sign = False
#     float_number = (fixed_point_number & ((1 << n_bits) - 1))
#     float_number *= 1.0 / (1 << n_fixed)
#     if sign:
#         return float_number
#     else:
#         return float_number * (-1.0)


# SymbolsSequenceFormat = namedtuple(
#     "SymbolsSequenceFormat",
#     ["name", "n_bits", "n_fixed", "is_signed", "size"])

# FcrClientFormat = namedtuple("FcrClientFormat", [
#     "resid_phase_h_format", "est_modulus_h_format", "resid_phase_v_format",
#     "est_modulus_v_format"
# ])
# fcr_client_format = FcrClientFormat(
#     resid_phase_h_format=SymbolsSequenceFormat(name="resid_phase_h",
#                                                n_bits=8,
#                                                n_fixed=8,
#                                                is_signed=False,
#                                                size=160),
#     est_modulus_h_format=SymbolsSequenceFormat(name="est_modulus_h",
#                                                n_bits=8,
#                                                n_fixed=5,
#                                                is_signed=False,
#                                                size=160),
#     resid_phase_v_format=SymbolsSequenceFormat(name="resid_phase_v",
#                                                n_bits=8,
#                                                n_fixed=8,
#                                                is_signed=False,
#                                                size=160),
#     est_modulus_v_format=SymbolsSequenceFormat(name="est_modulus_v",
#                                                n_bits=8,
#                                                n_fixed=5,
#                                                is_signed=False,
#                                                size=160))

# AdcClientFormat = namedtuple("AdcClientFormat", [
#     "datapath_a_hi_format", "datapath_b_hi_format", "datapath_a_hq_format",
#     "datapath_b_hq_format", "adc_fifo_sync_hi_format",
#     "adc_fifo_sync_hq_format", "adc_fifo_sync_vi_format",
#     "adc_fifo_sync_vq_format", "datapath_a_vi_format", "datapath_b_vi_format",
#     "datapath_a_vq_format", "datapath_b_vq_format"
# ])
# adc_client_format = AdcClientFormat(
#     datapath_a_hi_format=SymbolsSequenceFormat(name="datapath_a_hi",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     datapath_b_hi_format=SymbolsSequenceFormat(name="datapath_b_hi",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     datapath_a_hq_format=SymbolsSequenceFormat(name="datapath_a_hq",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     datapath_b_hq_format=SymbolsSequenceFormat(name="datapath_b_hq",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     adc_fifo_sync_hi_format=SymbolsSequenceFormat(name="adc_fifo_sync_hi",
#                                                   n_bits=1,
#                                                   n_fixed=0,
#                                                   is_signed=False,
#                                                   size=1),
#     adc_fifo_sync_hq_format=SymbolsSequenceFormat(name="adc_fifo_sync_hq",
#                                                   n_bits=1,
#                                                   n_fixed=0,
#                                                   is_signed=False,
#                                                   size=1),
#     adc_fifo_sync_vi_format=SymbolsSequenceFormat(name="adc_fifo_sync_vi",
#                                                   n_bits=1,
#                                                   n_fixed=0,
#                                                   is_signed=False,
#                                                   size=1),
#     adc_fifo_sync_vq_format=SymbolsSequenceFormat(name="adc_fifo_sync_vq",
#                                                   n_bits=1,
#                                                   n_fixed=0,
#                                                   is_signed=False,
#                                                   size=1),
#     datapath_a_vi_format=SymbolsSequenceFormat(name="datapath_a_vi",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     datapath_b_vi_format=SymbolsSequenceFormat(name="datapath_b_vi",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     datapath_a_vq_format=SymbolsSequenceFormat(name="datapath_a_vq",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120),
#     datapath_b_vq_format=SymbolsSequenceFormat(name="datapath_b_vq",
#                                                n_bits=8,
#                                                n_fixed=7,
#                                                is_signed=True,
#                                                size=120))

# DacClientFormat = namedtuple("DacClientFormat",
#                              ["dac_in_i_format", "dac_in_q_format"])

# dac_client_format = DacClientFormat(
#     dac_in_i_format=SymbolsSequenceFormat(name="dac_in_i",
#                                           n_bits=8,
#                                           n_fixed=7,
#                                           is_signed=True,
#                                           size=120),
#     dac_in_q_format=SymbolsSequenceFormat(name="dac_in_q",
#                                           n_bits=8,
#                                           n_fixed=7,
#                                           is_signed=True,
#                                           size=120))


# def get_formatted_du_data(du_data_cycle,
#                           client_format,
#                           last_word_n_data_bits=NB_BIT_PER_RF_REG):
#     str_bin_du_data_cycle = ""
#     for el in du_data_cycle[:(len(du_data_cycle) - 1)]:
#         str_bin_du_data_cycle += format(int(el),
#                                         "0{0}b".format(NB_BIT_PER_RF_REG))
#     str_bin_du_data_cycle += format(int(du_data_cycle[-1]),
#                                     "0{0}b".format(last_word_n_data_bits))
#     str_du_data_cycle = str_bin_du_data_cycle[::-1]
#     du_formatted_data = dict()
#     offset = 0
#     for sequence_format in client_format:
#         str_bin_symbols_sequence = str_du_data_cycle[offset:(
#             offset + sequence_format.n_bits * sequence_format.size)]
#         reverted_str_bin_sequences = [
#             str_bin_symbols_sequence[i:i + sequence_format.n_bits] for i in
#             range(0, len(str_bin_symbols_sequence), sequence_format.n_bits)
#         ]
#         str_bin_sequences = []
#         for reverted_str_bin_symbol in reverted_str_bin_sequences:
#             str_bin_sequences.append(reverted_str_bin_symbol[::-1])
#         symbols = []
#         for str_symbol in str_bin_sequences:
#             symbols.append(
#                 get_float_from_fixed_point(
#                     fixed_point_number=int(str_symbol, 2),
#                     n_bits=sequence_format.n_bits,
#                     n_fixed=sequence_format.n_fixed,
#                     is_signed=sequence_format.is_signed))
#         offset = offset + sequence_format.n_bits * sequence_format.size
#         du_formatted_data[sequence_format.name] = np.array(symbols)
#     return du_formatted_data


# # du_formats_dict = {DU_Signal_Source.DU_SIGNAL_SOURCE__ADC_OUTPUT: adc_client_format,
# #                    DU_Signal_Source.DU_SIGNAL_SOURCE__FCR_OUTPUT: fcr_client_format,
# #                    DU_Signal_Source.DU_SIGNAL_SOURCE__H_DAC_OUTPUT: dac_client_format,
# #                    DU_Signal_Source.DU_SIGNAL_SOURCE__V_DAC_OUTPUT: dac_client_format}

# du_formats_dict = {
#     1: adc_client_format,
#     2: fcr_client_format,
#     3: dac_client_format,
#     4: dac_client_format
# }


# class CanopusDuApi(object):
#     """CanopusDuApi base class"""
#     __metaclass__ = abc.ABCMeta

#     def __init__(self, api, du_signal_source):
#         """CanopusDuApi base class constructor. It expects an api object and a specific du signal source."""
#         self.api = api
#         self.du_signal_source = du_signal_source
#         self.data_format = du_formats_dict[du_signal_source]
#         self.run_du()
#         self.data = None

#     def run_du(self):
#         """Execute RunDiagnosticUnitCapture api with selected source in constructor"""
#         self.api.RunDiagnosticUnitCapture(self.du_signal_source)
#         self.data = None

#     def get_data(self, n_cycles):
#         """Return raw data executing GetDiagnosticUnitCaptureData as many times as necessary
#         to complete a DU read cycle. Only valid data elements are included"""
#         self.data = defaultdict(list)
#         for _ in range(n_cycles):
#             du_api_data_cycle = []
#             while True:
#                 #rsp = self.api.GetDiagnosticUnitCaptureData()
#                 #rsp = self.api.get_DiagnosticUnitCaptureData()
#                 rsp = self.api.get_diagnostic_unit_capture_data()
#                 print(rsp)

#                 du_api_data_cycle += rsp["data"][:rsp["valid_data_elements"]]
#                 if rsp["remaining_pages"] == 0:
#                     break
            
#             # f1 = open('./static/files/duAdcCapRaw.csv','r')
#             # for item in f1.readlines():
#             #     du_api_data_cycle.append(int(item))

#             print("du_api_data_cycle begin xxx---------------------------------------")
#             print(du_api_data_cycle)
#             print("du_api_data_cycle end-----------------------------------------")

#             raw_data_cycle = np.array(du_api_data_cycle, dtype=np.int64)
#             formatted_data_cycle = get_formatted_du_data(
#                 raw_data_cycle, self.data_format)
#             for key in formatted_data_cycle:
#                 self.data[key] = np.concatenate(
#                     [self.data[key], formatted_data_cycle[key]])
#         return self.data

#     @abc.abstractmethod
#     def show(self):
#         pass


# class FcrDu(CanopusDuApi):
#     def __init__(self, api):
#         """FcrDu class constructor. It expects an api object"""
#         CanopusDuApi.__init__(
#             self, api, 2)  #DU_Signal_Source.DU_SIGNAL_SOURCE__FCR_OUTPUT

#     def show(self, n_cycles=1):
#         """Show constellation diagram and return figure handler object"""
#         self.get_data(n_cycles)
#         #is_qpsk = self.api.GetTransceiverMode()["line_modulation"] == Line_Modulation.LM_QPSK
#         is_qpsk = self.api.get_transceiver_mode()["line_modulation"] == 4

#         data_keys_pairs = ((fcr_client_format.est_modulus_h_format.name,
#                             fcr_client_format.resid_phase_h_format.name),
#                            (fcr_client_format.est_modulus_v_format.name,
#                             fcr_client_format.resid_phase_v_format.name))

#         rect = [-3, 3, -3, 3] if is_qpsk else [-5, 5, -5, 5]
#         handler = figure(figsize=(14, 6))
#         polarizations = ("h", "v")
#         plot_colors = ("b.", "r.")

#         for idx, (modulus_key, phase_key) in enumerate(data_keys_pairs):
#             subplot(1, 2, idx + 1)
#             xlabel("{0}i".format(polarizations[idx]))
#             ylabel("{0}q".format(polarizations[idx]))
#             xx = [
#                 modulus * cos(phase * 2 * pi) for modulus, phase in zip(
#                     self.data[modulus_key], self.data[phase_key])
#             ]
#             yy = [
#                 modulus * sin(phase * 2 * pi) for modulus, phase in zip(
#                     self.data[modulus_key], self.data[phase_key])
#             ]
#             if len(xx) < 6000:
#                 plot(xx, yy, plot_colors[idx])
#             else:
#                 histogram, x_edges, y_edges = np.histogram2d(xx,
#                                                              yy,
#                                                              bins=[100, 100])
#                 h_masked = np.ma.masked_where(histogram == 0, histogram)
#                 extent = [x_edges[0], x_edges[-1], y_edges[0], y_edges[-1]]
#                 imshow(h_masked.T,
#                        extent=extent,
#                        interpolation='nearest',
#                        origin='lower',
#                        aspect='auto')
#             axis(rect)
#             grid()
#         # show(block=True)

#         # return handler

#         # save picture to web dir #####################################################
#         tt = str(time.time())
#         handler.savefig('./static/files/plot' + tt + '.png')

#         close('all')
#         # time.sleep(1)
#         return 'plot' + tt + '.png'


# class AdcDu(CanopusDuApi):
#     def __init__(self, api):
#         """AdcDu class constructor. It expects an api object"""
#         CanopusDuApi.__init__(
#             self, api, 1)  #DU_Signal_Source.DU_SIGNAL_SOURCE__ADC_OUTPUT

#     def show(self, n_cycles=1):
#         """Show eye diagram and ADC waveforms per line lane and return figure handler object"""
#         print('xxxxx')
#         self.get_data(n_cycles)
#         #print(self.data)

#         data_keys = (adc_client_format.datapath_b_hi_format.name,
#                      adc_client_format.datapath_b_hq_format.name,
#                      adc_client_format.datapath_b_vi_format.name,
#                      adc_client_format.datapath_b_vq_format.name)
#         labels = "hi", "hq", "vi", "vq"
#         colours = ("b", "y") * 2
#         ax = (0, 15, -1, 1)
#         osr = 8.
#         #osr_in = 1.2 if self.api.GetTransceiverMode()["lrx_osr"] == Osr_Line.SIX_OVER_FIVE else 1.5
#         osr_in = 1.2 if self.api.get_transceiver_mode(
#         )["lrx_osr"] == 2 else 1.5  #SIX_OVER_FIVE

#         data_to_be_plotted = list()
#         for key in data_keys:
#             data_to_be_plotted.append(self.data[key].tolist())
#         handler = figure(figsize=(14, 8))
#         data_int = []
#         for i, d in enumerate(data_to_be_plotted):
#             t = np.arange(0, len(d) / osr_in, 1 / osr_in)
#             tt = np.arange(0, t[-1], 1 / float(osr))
#             m = min([len(t), len(d)])
#             dataa = interpolate.interp1d(t[0:m], d[0:m], kind='cubic')(tt)
#             data_ax = dataa[int(len(dataa) % 16)::][int(osr * 16):int(-osr *
#                                                                       16):]
#             data_int.append(dataa)
#             x = np.transpose(
#                 np.reshape(data_ax,
#                            (len(data_ax) // int(2 * osr), int(2 * osr))))
#             subplot(len(data_to_be_plotted), 2, i * 2 + 1)
#             ylabel(labels[i])
#             plot(x, colours[i])
#             axis(ax)
#             grid()

#         for i, d in enumerate(data_int):
#             subplot(len(data_to_be_plotted), 2, i * 2 + 2)
#             plot(d, ".-{0}".format(colours[i]))
#             axis([0, len(d), ax[2], ax[3]])
#             grid()
#         show(block=True)

#         #return handler

#         # save picture to web dir #####################################################
#         tt = str(time.time())
#         handler.savefig('./static/files/plot' + tt + '.png')
#         close('all')
#         # time.sleep(1)
#         return 'plot' + tt + '.png'


# class HDacDu(CanopusDuApi):
#     def __init__(self, api):
#         CanopusDuApi.__init__(
#             self, api, 3)  #DU_Signal_Source.DU_SIGNAL_SOURCE__H_DAC_OUTPUT
#         self.data = None

#     def show(self, n_cycles=1):
#         """Show eye diagram and DAC waveforms per line lane and return figure handler object"""
#         self.get_data(n_cycles)
#         data_keys = (dac_client_format.dac_in_i_format.name,
#                      dac_client_format.dac_in_q_format.name)
#         labels = "hi", "hq"
#         colours = ("b", "y")
#         ax = (0, 15, -1, 1)
#         osr = 8.
#         osr_in = 1.2 if self.api.GetTransceiverMode(
#         )["lrx_osr"] == Osr_Line.SIX_OVER_FIVE else 1.5

#         data_to_be_plotted = list()
#         for key in data_keys:
#             data_to_be_plotted.append(self.data[key].tolist())
#         handler = figure(figsize=(14, 8))
#         data_int = []
#         for i, d in enumerate(data_to_be_plotted):
#             t = np.arange(0, len(d) / osr_in, 1 / osr_in)
#             tt = np.arange(0, t[-1], 1 / float(osr))
#             m = min([len(t), len(d)])
#             dataa = interpolate.interp1d(t[0:m], d[0:m], kind='cubic')(tt)
#             data_ax = dataa[int(len(dataa) % 16)::][int(osr * 16):int(-osr *
#                                                                       16):]
#             data_int.append(dataa)
#             x = np.transpose(
#                 np.reshape(data_ax,
#                            (len(data_ax) / int(2 * osr), int(2 * osr))))
#             subplot(len(data_to_be_plotted), 2, i * 2 + 1)
#             ylabel(labels[i])
#             plot(x, colours[i])
#             axis(ax)
#             grid()

#         for i, d in enumerate(data_int):
#             subplot(len(data_to_be_plotted), 2, i * 2 + 2)
#             plot(d, ".-{0}".format(colours[i]))
#             axis([0, len(d), ax[2], ax[3]])
#             grid()
#         show(block=True)

#         return handler


# class VDacDu(CanopusDuApi):
#     def __init__(self, api):
#         CanopusDuApi.__init__(
#             self, api, 4)  #DU_Signal_Source.DU_SIGNAL_SOURCE__V_DAC_OUTPUT
#         self.data = None

#     def show(self, n_cycles=1):
#         """Show eye diagram and DAC waveforms per line lane and return figure handler object"""
#         self.get_data(n_cycles)
#         data_keys = (dac_client_format.dac_in_i_format.name,
#                      dac_client_format.dac_in_q_format.name)
#         labels = "vi", "vq"
#         colours = ("b", "y") * 2
#         ax = (0, 15, -1, 1)
#         osr = 8.
#         osr_in = 1.2 if self.api.GetTransceiverMode(
#         )["lrx_osr"] == Osr_Line.SIX_OVER_FIVE else 1.5

#         data_to_be_plotted = list()
#         for key in data_keys:
#             data_to_be_plotted.append(self.data[key].tolist())
#         handler = figure(figsize=(14, 8))
#         data_int = []
#         for i, d in enumerate(data_to_be_plotted):
#             t = np.arange(0, len(d) / osr_in, 1 / osr_in)
#             tt = np.arange(0, t[-1], 1 / float(osr))
#             m = min([len(t), len(d)])
#             dataa = interpolate.interp1d(t[0:m], d[0:m], kind='cubic')(tt)
#             data_ax = dataa[int(len(dataa) % 16)::][int(osr * 16):int(-osr *
#                                                                       16):]
#             data_int.append(dataa)
#             x = np.transpose(
#                 np.reshape(data_ax,
#                            (len(data_ax) / int(2 * osr), int(2 * osr))))
#             subplot(len(data_to_be_plotted), 2, i * 2 + 1)
#             ylabel(labels[i])
#             plot(x, colours[i])
#             axis(ax)
#             grid()

#         for i, d in enumerate(data_int):
#             subplot(len(data_to_be_plotted), 2, i * 2 + 2)
#             plot(d, ".-{0}".format(colours[i]))
#             axis([0, len(d), ax[2], ax[3]])
#             grid()
#         show(block=True)

#         return handler


# ######################################################################################
# @module_bp.route('/mod_constellation')
# def mod_constellation():
#     return render_template('mod_constellation.html', title='Constellation',for_customer=for_customer)


# @module_bp.route('/api/btn_empty_cache')
# def btn_empty_cache():
#     # os.system("command")
#     # os.system("del /Q ./static/files/*.png")
#     os.system("clean.bat")
#     return "empty cache ok."


# # this funtion only for test
# # @module_bp.route('/api/btn_fcr_capture_show')
# # def btn_fcr_capture_show():
# #     time.sleep(0.1)
# #     y = []
# #     for i in range(1, 11):
# #         y.append(random.randint(10,50))

# #     x = np.arange(10)
# #     fig = plt.figure()
# #     ax = plt.subplot(111)
# #     ax.plot(x, y, label='$y = numbers')
# #     plt.title('Legend inside')
# #     ax.legend()
# #     # plt.show()
# #     tt = str(time.time())
# #     # ./static/files/voa.csv
# #     fig.savefig('./static/files/plot' + tt +'.png')

# #     # fig.savefig('../php/plot.png')
# #     plt.close('all')
# #     # time.sleep(1)
# #     return 'files/plot' + tt +'.png'


# @module_bp.route('/api/btn_fcr_capture_show')
# def btn_fcr_capture_show():
#     ret = fcr_output_capture()
#     return ret


# def fcr_output_capture():
#     print("fcr_output_capture")
#     b = Broker()
#     dsp = Canopus(b)
#     FCR_cap = FcrDu(dsp)
#     #FCR_cap.get_data()
#     FCR_cap.run_du()
#     ret = FCR_cap.show(1)
#     return ret
#     # ret = demo_capture()
#     # return ret


# @module_bp.route('/api/btn_adc_capture_show')
# def btn_adc_capture_show():
#     ret = adc_output_capture()
#     return ret


# def adc_output_capture():
#     print("adc_output_capture")
#     b = Broker()
#     dsp = Canopus(b)
#     ADC_cap = AdcDu(dsp)
#     #FCR_cap.get_data()
#     ADC_cap.run_du()
#     ret = ADC_cap.show(1)
#     return ret


# ##################################################
# # PRBS
# ##################################################
# @module_bp.route('/api/set_password')
# def set_password():
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     return "set_password, ok"


# @module_bp.route('/prbs')
# def prbs():
#     return render_template('prbs.html', title='PRBS',for_customer=for_customer)


# @module_bp.route('/api/btn_line_side_prbs_config_enble', methods=['POST'])
# def btn_line_side_prbs_config_enble():
#     print("btn_line_side_prbs_config_enble ...")
#     p1 = request.form["p1"]
#     print(p1)
#     b = Broker()
#     dsp = Canopus(b)
#     ret1 = str(dsp.SetCoreCfecTestPatternGeneratorConfig(int(p1), 1))
#     ret2 = str(dsp.SetCoreCfecTestPatternCheckerConfig(int(p1), 1))
#     print(ret1)
#     print(ret2)
#     return 'btn_line_side_prbs_config_enble, ok.'


# @module_bp.route('/api/btn_line_side_prbs_config_disable', methods=['POST'])
# def btn_line_side_prbs_config_disable():
#     print("btn_line_side_prbs_config_disable ...")
#     p1 = request.form["p1"]
#     print(p1)
#     b = Broker()
#     dsp = Canopus(b)
#     ret1 = str(dsp.SetCoreCfecTestPatternGeneratorConfig(int(p1), 0))
#     ret2 = str(dsp.SetCoreCfecTestPatternCheckerConfig(int(p1), 0))
#     print(ret1)
#     print(ret2)
#     return 'btn_line_side_prbs_config_disable, ok.'


# @module_bp.route('/api/btn_host_side_prbs_config_enble', methods=['POST'])
# def btn_host_side_prbs_config_enble():
#     print("btn_host_side_prbs_config_enble ...")
#     b = Broker()
#     dsp = Canopus(b)
#     ret1 = str(dsp.SetPcsTestPatternGeneratorConfig(4, 1, 1, 1))
#     ret2 = str(dsp.SetPcsTestPatternCheckerConfig(4, 2, 1, 1))
#     print(ret1)
#     print(ret2)
#     return 'btn_host_side_prbs_config_enble, ok.'


# @module_bp.route('/api/btn_host_side_prbs_config_disable', methods=['POST'])
# def btn_host_side_prbs_config_disable():
#     print("btn_host_side_prbs_config_disable ...")
#     b = Broker()
#     dsp = Canopus(b)
#     ret1 = str(dsp.SetPcsTestPatternGeneratorConfig(4, 1, 1, 0))
#     ret2 = str(dsp.SetPcsTestPatternCheckerConfig(4, 2, 1, 0))
#     print(ret1)
#     print(ret2)
#     return 'btn_host_side_prbs_config_disable, ok.'


# @module_bp.route('/api/btn_line_side_prbs', methods=['POST'])
# def btn_line_side_prbs():
#     print("btn_line_side_prbs ...")
#     b = Broker()
#     dsp = Canopus(b)
#     # ret = dsp.GetCoreCfecTestPatternCheckerCounters()
#     ret = dsp.get_core_cfec_test_pattern_checker_counters()
#     print(ret)
#     print(type(ret))
#     return json.dumps(ret)


# @module_bp.route('/api/btn_host_side_prbs', methods=['POST'])
# def btn_host_side_prbs():
#     print("btn_host_side_prbs ...")
#     b = Broker()
#     dsp = Canopus(b)
#     # ret = dsp.GetPcsTestPatternCheckerStatistics(4,2)
#     ret = dsp.get_pcs_test_pattern_checker_statistics(4, 2)
#     print(ret)
#     print(type(ret))
#     return json.dumps(ret)



# @module_bp.route('/prbs2')
# def prbs2():
#     return render_template('prbs2.html', title='PRBS',for_customer=for_customer)

# @module_bp.route('/api/btn_host_gen_en', methods=['POST'])
# def btn_host_gen_en():
#     print("btn_host_gen_en ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_host_gen_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.host_gen_prbs_set(lane, val)

#     cmis.host_gen = 1
#     return 'btn_host_gen_en, ok.'

# @module_bp.route('/api/btn_host_gen_dis', methods=['POST'])
# def btn_host_gen_dis():
#     print("btn_host_gen_dis ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_host_gen_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.host_gen_prbs_set(lane, val)

#     cmis.host_gen = 0
#     return 'btn_host_gen_dis, ok.'

# @module_bp.route('/api/btn_host_chk_en', methods=['POST'])
# def btn_host_chk_en():
#     print("btn_host_chk_en ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_host_chk_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.host_chk_prbs_set(lane, val)

#     cmis.host_chk = 1
#     return 'btn_host_chk_en, ok.'

# @module_bp.route('/api/btn_host_chk_dis', methods=['POST'])
# def btn_host_chk_dis():
#     print("btn_host_chk_dis ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_host_chk_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.host_chk_prbs_set(lane, val)

#     cmis.host_chk = 0
#     return 'btn_host_chk_dis, ok.'

# @module_bp.route('/api/btn_line_gen_en', methods=['POST'])
# def btn_line_gen_en():
#     print("btn_line_gen_en ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_line_gen_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.media_gen_prbs_set(lane, val)

#     cmis.media_gen = 1
#     return 'btn_line_gen_en, ok.'

# @module_bp.route('/api/btn_line_gen_dis', methods=['POST'])
# def btn_line_gen_dis():
#     print("btn_line_gen_dis ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_line_gen_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.media_gen_prbs_set(lane, val)

#     cmis.media_gen = 0
#     return 'btn_line_gen_dis, ok.'

# @module_bp.route('/api/btn_line_chk_en', methods=['POST'])
# def btn_line_chk_en():
#     print("btn_line_chk_en ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_line_chk_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.media_chk_prbs_set(lane, val)

#     cmis.media_chk = 1
#     return 'btn_line_chk_en, ok.'

# @module_bp.route('/api/btn_line_chk_dis', methods=['POST'])
# def btn_line_chk_dis():
#     print("btn_line_chk_dis ...")
#     b = Broker()
#     cmis = CMIS(b)
#     val = int(request.form["btn_line_chk_type"])
#     for lane in [0,1,2,3,4,5,6,7]:
#         cmis.media_chk_prbs_set(lane, val)

#     cmis.media_chk = 0
#     return 'btn_line_chk_dis, ok.'


# @module_bp.route('/api/get_prbs_config_state', methods=['GET'])
# def get_prbs_config_state():
#     print("get_prbs_config_state ...")
#     b = Broker()
#     cmis = CMIS(b)

#     ret = {
#         'btn_host_gen' : cmis.host_gen,
#         'btn_host_chk' : cmis.host_chk,
#         'btn_line_gen' : cmis.media_gen,
#         'btn_line_chk' : cmis.media_chk,
#         'btn_host_gen_type' : cmis.host_gen_prbs_get(0),
#         'btn_host_chk_type' : cmis.host_chk_prbs_get(0),
#         'btn_line_gen_type' : cmis.media_gen_prbs_get(0),
#         'btn_line_chk_type' : cmis.media_chk_prbs_get(0),
#     }
#     return json.dumps(ret)




# @module_bp.route('/prbs1')
# def prbs1():
#     return render_template('prbs1.html', title='PRBS',for_customer=for_customer)


# @module_bp.route('/api/btn_host_side_prbs_config_enble1', methods=['POST'])
# def btn_host_side_prbs_config_enble1():
#     print("btn_host_side_prbs_config_enble1 ...")
#     b = Broker()
#     cmis = CMIS(b)
#     cmis.host_gen = 1
#     cmis.host_chk = 1
#     return 'btn_host_side_prbs_config_enble1, ok.'


# @module_bp.route('/api/btn_host_side_prbs_config_disable1', methods=['POST'])
# def btn_host_side_prbs_config_disable1():
#     print("btn_host_side_prbs_config_disable1 ...")
#     b = Broker()
#     dsp = Canopus(b)
#     cmis = CMIS(b)
#     cmis.host_chk = 0
#     cmis.host_gen = 0
#     return 'btn_host_side_prbs_config_disable1, ok.'


# @module_bp.route('/api/btn_line_side_prbs_config_enble1', methods=['POST'])
# def btn_line_side_prbs_config_enble1():
#     print("btn_line_side_prbs_config_enble1 ...")
#     b = Broker()
#     cmis = CMIS(b)
#     cmis.media_gen = 1
#     cmis.media_chk = 1
#     return 'btn_line_side_prbs_config_enble1, ok.'


# @module_bp.route('/api/btn_line_side_prbs_config_disable1', methods=['POST'])
# def btn_line_side_prbs_config_disable1():
#     print("btn_line_side_prbs_config_disable1 ...")
#     b = Broker()
#     cmis = CMIS(b)
#     cmis.media_chk = 0
#     cmis.media_gen = 0
#     return 'btn_line_side_prbs_config_disable1, ok.'


# @module_bp.route('/api/btn_host_side_prbs1', methods=['POST'])
# def btn_host_side_prbs1():
#     print("btn_host_side_prbs1 ...")
#     b = Broker()
#     cmis = CMIS(b)
#     info_list_all = []

#     cmis.dign_sel = 0x02
#     #  cmis.dign_info
#     # {'Host Lane 1 ERROR COUNT': 0, 'Host Lane 1 BIT COUNT': 0, 
#     # 'Host Lane 2 ERROR COUNT': 0, 'Host Lane 2 BIT COUNT': 0, 
#     # 'Host Lane 3 ERROR COUNT': 0, 'Host Lane 3 BIT COUNT': 0, 
#     # 'Host Lane 4 ERROR COUNT': 0, 'Host Lane 4 BIT COUNT': 0}
#     info_dict = cmis.dign_info
#     L1 = [
#         ['Host Lane 1', info_dict['Host Lane 1 ERROR COUNT'],  info_dict['Host Lane 1 BIT COUNT'],  0 if info_dict['Host Lane 1 BIT COUNT']==0 else info_dict['Host Lane 1 ERROR COUNT'] / info_dict['Host Lane 1 BIT COUNT']],
#         ['Host Lane 2', info_dict['Host Lane 2 ERROR COUNT'],  info_dict['Host Lane 2 BIT COUNT'],  0 if info_dict['Host Lane 2 BIT COUNT']==0 else info_dict['Host Lane 2 ERROR COUNT'] / info_dict['Host Lane 2 BIT COUNT']],
#         ['Host Lane 3', info_dict['Host Lane 3 ERROR COUNT'],  info_dict['Host Lane 3 BIT COUNT'],  0 if info_dict['Host Lane 3 BIT COUNT']==0 else info_dict['Host Lane 3 ERROR COUNT'] / info_dict['Host Lane 3 BIT COUNT']],
#         ['Host Lane 4', info_dict['Host Lane 4 ERROR COUNT'],  info_dict['Host Lane 4 BIT COUNT'],  0 if info_dict['Host Lane 4 BIT COUNT']==0 else info_dict['Host Lane 4 ERROR COUNT'] / info_dict['Host Lane 4 BIT COUNT']],
#     ]

#     cmis.dign_sel = 0x03 #Lane5 ~ 8
#     info_dict = cmis.dign_info
#     L2 = [
#         ['Host Lane 5', info_dict['Host Lane 5 ERROR COUNT'],  info_dict['Host Lane 5 BIT COUNT'],  0 if info_dict['Host Lane 5 BIT COUNT']==0 else info_dict['Host Lane 5 ERROR COUNT'] / info_dict['Host Lane 5 BIT COUNT']],
#         ['Host Lane 6', info_dict['Host Lane 6 ERROR COUNT'],  info_dict['Host Lane 6 BIT COUNT'],  0 if info_dict['Host Lane 6 BIT COUNT']==0 else info_dict['Host Lane 6 ERROR COUNT'] / info_dict['Host Lane 6 BIT COUNT']],
#         ['Host Lane 7', info_dict['Host Lane 7 ERROR COUNT'],  info_dict['Host Lane 7 BIT COUNT'],  0 if info_dict['Host Lane 7 BIT COUNT']==0 else info_dict['Host Lane 7 ERROR COUNT'] / info_dict['Host Lane 7 BIT COUNT']],
#         ['Host Lane 8', info_dict['Host Lane 8 ERROR COUNT'],  info_dict['Host Lane 8 BIT COUNT'],  0 if info_dict['Host Lane 8 BIT COUNT']==0 else info_dict['Host Lane 8 ERROR COUNT'] / info_dict['Host Lane 8 BIT COUNT']],
#     ]
#     return json.dumps(L1+L2)




# @module_bp.route('/api/btn_line_side_prbs1', methods=['POST'])
# def btn_line_side_prbs1():
#     print("btn_line_side_prbs1 ...")
#     b = Broker()
#     cmis = CMIS(b)
#     info_list_all = []

#     cmis.dign_sel = 0x04
#     #  cmis.dign_info

#     # cmis.dign_info
#     # {'Media Lane 1 ERROR COUNT': 0, 'Media Lane 1 BIT COUNT': 0, 
#     # 'Media Lane 2 ERROR COUNT': 0, 'Media Lane 2 BIT COUNT': 0, 
#     # 'Media Lane 3 ERROR COUNT': 0, 'Media Lane 3 BIT COUNT': 0, 
#     # 'Media Lane 4 ERROR COUNT': 0, 'Media Lane 4 BIT COUNT': 0}

#     # Lane 1
#     info_dict = cmis.dign_info
#     L1 = [
#         ['Media Lane 1', info_dict['Media Lane 1 ERROR COUNT'],  info_dict['Media Lane 1 BIT COUNT'],  0 if info_dict['Media Lane 1 BIT COUNT']==0 else info_dict['Media Lane 1 ERROR COUNT'] / info_dict['Media Lane 1 BIT COUNT']],
#     ]

#     return json.dumps(L1)



# @module_bp.route('/api/data_clear', methods=['POST'])
# def data_clear():
#     print("data_clear ...")
#     b = Broker()
#     cmis = CMIS(b)
#     cmis.dign_rst = 1
#     time.sleep(2)
#     cmis.dign_rst = 0
#     return 'data_clear, ok.'



# @module_bp.route('/auto_fan')
# def auto_fan():
#     return render_template('auto_fan.html', title='Auto Fan',for_customer=for_customer)


# @module_bp.route('/api/auto_fan_init')
# def auto_fan_init():
#     fan_dict = {}
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     d = DDM(b)

#     fan_dict.update({"case_temp": round(d.case_temp, 2)})
#     # fan_dict.update({"fan_rate": 20})
#     # fan_dict.update({"target_temp": 55})

#     return json.dumps(fan_dict)


# @module_bp.route('/api/check_fan', methods=['POST'])
# def check_fan():
#     PADDING = 1.5
#     check_fan_dict = {}
#     check_fan_dict.update({"state": "OK"})
#     check_fan_dict.update({"msg": "---"})

#     target_temp = int(request.form["target_temp"])
#     fan_rate = int(request.form["fan_rate"])
#     # fan_step = 1

#     print("check_fan ... ... ...")
#     # 1. check module ready?
#     module_state_map = {
#         '000': 'Reserved',
#         '001': 'LowPwr',
#         '010': 'PwrUp',
#         '011': 'Ready',
#         '100': 'PwrDn',
#         '101': 'Fault',
#         '110': 'Reserved',
#         '111': 'Reserved'
#     }
#     ret = a.get_twi(1, 0x3)
#     ret1 = ret.split(',')[0]  #hex
#     ret2 = int(ret1, 16)

#     idx = '{:08b}'.format(ret2)[4:7]
#     if module_state_map[idx] == 'Ready':
#         pass
#     else:
#         # return "Please set module ready firstly!"
#         check_fan_dict.update({"state": "FAILED"})
#         check_fan_dict.update({"msg": "Please set module ready firstly!"})
#         return json.dumps(check_fan_dict)

#     #2. set fan_rate
#     a.comm_cmdstr_setter('*FAN ' + str(fan_rate))

#     # 3. target temp: 55
#     print("target_temp:", target_temp)
#     print("fan_rate:", fan_rate)

#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#     d = DDM(b)
#     case_temp = round(d.case_temp, 2)

#     if fan_rate < 0 and fan_rate > 100:
#         check_fan_dict.update({"state": "FAILED"})
#         check_fan_dict.update({"msg": "UNKNOWN ERROR"})
#     else:
#         if target_temp == 55:
#             # target temp: 55 level
#             if abs(case_temp - int(target_temp)) < PADDING:
#                 check_fan_dict.update({"state": "DONE"})
#                 check_fan_dict.update({"msg": "Fan adjustment completed."})
#             else:
#                 fan_rate = fan_rate + 3
#                 check_fan_dict.update({"fan_rate": fan_rate})
#                 a.comm_cmdstr_setter('*FAN ' + str(fan_rate))
#                 check_fan_dict.update({"case_temp": case_temp})
#                 time.sleep(1)
#         else:
#             # target temp: 75 level
#             if abs(case_temp - int(target_temp)) < PADDING:
#                 check_fan_dict.update({"state": "DONE"})
#                 check_fan_dict.update({"msg": "Fan adjustment completed."})
#             else:
#                 fan_rate = fan_rate + 1
#                 check_fan_dict.update({"fan_rate": fan_rate})
#                 a.comm_cmdstr_setter('*FAN ' + str(fan_rate))
#                 check_fan_dict.update({"case_temp": case_temp})
#                 time.sleep(1)

#     return json.dumps(check_fan_dict)


# @module_bp.route('/api/set_fan_rate2', methods=['POST'])
# def set_fan_rate2():
#     check_fan_dict = {}
#     check_fan_dict.update({"state": "OK"})
#     check_fan_dict.update({"msg": "---"})
#     fan_rate = int(request.form["fan_rate"]) + 1
#     a.comm_cmdstr_setter('*FAN ' + str(fan_rate))
#     print("fan_rate:", fan_rate)
#     return json.dumps(check_fan_dict)



# @module_bp.route('/export', methods=['GET'])
# def export():
#     return render_template('export.html', title='Export Data')



# analog1 = {
#     'P3V3_OSFP_CURR_CHECK': 100,
#     'P3V3_OSFP': 101,
#     'P3V3_OSFP_CON': 102,
#     'P1V0_FPGA': 103,
#     'P1V8_FPGA_OSFP': 104,
#     'MODULE_CASE_TEMP1': 105,
#     'P3V3_FPGA': 106,
#     'P2V5_REF': 107,
#     'Temperature_1': 108,
#     'Temperature_2': 109,
#     'P5V_USB_DEBUG': 110,
#     'Module_Power': 111,
#     'P3V3_VccTX': 112,
#     'P3V3_VccRX': 113
# }

# @module_bp.route('/api/btn_export_parameters', methods=['POST'])
# def btn_export_parameters():

#     # get user selected!
#     ckb_ANALOG = request.form["ckb_ANALOG"]
#     ckb_MSA = request.form["ckb_MSA"]
#     ckb_PIN = request.form["ckb_PIN"]
#     ckb_ADC = request.form["ckb_ADC"]
#     ckb_DAC = request.form["ckb_DAC"]
#     ckb_DDM = request.form["ckb_DDM"]
#     ckb_MODULE_INFO = request.form["ckb_MODULE_INFO"]
#     ckb_PAGES_DATA = request.form["ckb_PAGES_DATA"]

#     setdefaulttimeout(200000)
#     b = Broker()
#     b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')

#     wb = Workbook()
#     # parameters_file = 'parameters.xlsx'
#     # ANALOG-------------------------------------------------------------
#     if ckb_ANALOG == 'ANALOG':
#         print('Export ANALOG info ...')
#         sheet_analog = wb.create_sheet('ANALOG',index=0)
#         sheet_analog.append(['Name', 'Value']) 
#         for item in analog1.keys():
#             item_val = analog1[item]
#             cell_val = a.ain_get(int(item_val))
#             row = [item, cell_val.split(',')[1]]
#             print(row)
#             sheet_analog.append(row)

#     # MSA-------------------------------------------------------------
#     if ckb_MSA == 'MSA':
#         print('Export MSA info ...')
#         sheet_msa = wb.create_sheet('MSA',index=0)
#         sheet_msa.append(['Name', 'Value']) 
#         # Module State    ----------------------------------------------
#         sheet_msa.append(['Module State', get_module_state()])
#         sheet_msa.append(['Data Path State', get_dp_state()])
#         # -------------------------------------------------------------
#         sheet_msa.append(['Programmable Output Power Supported', get_pops()])
#         sheet_msa.append(['Min Program Output Power', get_min_pop()])
#         sheet_msa.append(['Max Program Output Power', get_max_pop()])
#         sheet_msa.append(['Program Output Power', get_pop()])
#         # -------------------------------------------------------------
#         sheet_msa.append(['P3V3',  a.aout_get(101).split(",")[0]])
#         sheet_msa.append(['TWI Interface', "FPGA" if a.din_get(5) == 0 else "MCU"  ])
#         sheet_msa.append(['Rate',  a.get_twi_rate()])
#         sheet_msa.append(['RSTN', "Reset" if a.dout_get(20) == 0 else  "No Reset"])
#         sheet_msa.append(['LPWN', "High Power Up" if a.dout_get(21) == 0 else  "Low Power"])
#         sheet_msa.append(['INTN', "INTN High" if a.din_get(1) == 0 else  "INTN Low"])
#         sheet_msa.append(['PRSN', "No Module" if a.din_get(2) == 0 else  "Module Present"])
#         sheet_msa.append(['Module Power', "OFF" if a.dout_get(27) == 0 else  "ON"])

#     # PIN-------------------------------------------------------------
#     if ckb_PIN == 'PIN':
#         print('Export PIN info ...')
#         sheet_pin = wb.create_sheet('PIN',index=0)
#         sheet_pin.append(['Name', 'State']) 
#         for item in mod_pin_1_items:
#             time.sleep(0.06)
#             d = DPin(b, item[0])
#             row = [item[0], d.state]
#             print(row)
#             sheet_pin.append(row) 

#         for item in mod_pin_2_items:
#             time.sleep(0.06)
#             d = DPin(b, item[0])
#             row = [item[0], d.state]
#             print(row)
#             sheet_pin.append(row) 

#         for item in mod_pin_3_items:
#             time.sleep(0.06)
#             d = DPin(b, item[0])
#             row = [item[0], d.state]
#             print(row)
#             sheet_pin.append(row) 

#     # ADC-------------------------------------------------------------
#     if ckb_ADC == 'ADC':
#         print('Export ADC info...')
#         sheet_adc = wb.create_sheet('ADC',index=0)
#         sheet_adc.append(['Name', 'Aval', 'Rawval', 'Dval']) 

#         item_list = [
#             'TX_VOA_X', 'TX_VOA_X_I', 'TX_VOA_Y', 'TX_VOA_Y_I', 'RX_VOA_X',
#             'RX_VOA_X_I', 'RX_VOA_Y', 'RX_VOA_Y_I', 'RX_MPD_X_MCU2', 'RX_MPD_Y_MCU2'
#         ]

#         for item in adc_items:
#             ain = Ain(b, item[0])
#             if item[0] in item_list:
#                 val_a = ain.val_a
#                 # cells_val = str(val_a[0]) + ',' + str(round(val_a[1], 6)) + ',' + str(round(val_a[2], 6))
#                 row = [item[0], str(round(val_a[1], 6)), str(round(val_a[2], 6)), str(val_a[0]) ]
#             else:
#                 val = ain.val
#                 # cells_val = str(val[0]) + ',' + str(round(val[1], 3)) + ',' + str(round(val[2], 3))
#                 row = [item[0], str(round(val[1], 3)), str(round(val[2], 3)), str(val[0]) ]

#             print(row)
#             sheet_adc.append(row)

#     #DAC-------------------------------------------------------------
#     if ckb_DAC == 'DAC':
#         print('Export DAC info ....')
#         sheet_dac = wb.create_sheet('DAC',index=0)
#         row = ['Name', 'Aval', 'Rawval', 'Dval']
#         sheet_dac.append(row) 

#         for item in dac_items:
#             aout = Aout(b, item[0])
#             # cells_val = str(round(a.aval, 4)) + ',' + str(a.dval) + ',' + str(round(a.raw_aval, 4))
#             row = [item[0], str(round(aout.aval, 4)) , str(round(aout.raw_aval, 4)) , str(aout.dval)]
#             print(row)
#             sheet_dac.append(row) 
#             time.sleep(0.01)


#     # MODULE INFO-------------------------------------------------------------
#     if ckb_MODULE_INFO == 'MODULE_INFO':
#         print('Export MODULE info ....')
#         sheet_modinfo = wb.create_sheet('MODULE INFO',index=0)
#         sheet_modinfo.append(['Name', 'Value']) 
#         mod_info_all = {
#             "a_mcu_ver":"---",
#             "a_sub_mcu_ver":"---",
#             "a_dsp_ver":"---",
#             "a_running":"---",
#             "a_commited":"---",
#             "b_mcu_ver":"---",
#             "b_sub_mcu_ver":"---",
#             "b_dsp_ver":"---",
#             "b_running":"---",
#             "b_commited":"---",
#             "pcbm_ver":"---",
#             "pcbs_ver":"---",
#             "dsp_ver":"---",
#             "cosa_ver":"---",
#             "itla_ver":"---",
#             "module_config_table_ver":"---",
#             "vendor_name":"---",
#             "vendor_pn":"---",
#             "vendor_sn":"---"
#         }


#         b = Broker()
#         cdb = CDB(b)
#         cmis = CMIS(b)
#         rlplen, rlp_chkcode, rlp = cdb.CMD0100h()
#         if b.cdb_chkcode(rlp) == rlp_chkcode:
#             fwStaus = rlp[0]  #136
#             mod_info_all['a_running'] = (fwStaus & 0x01)
#             mod_info_all['a_commited'] = ((fwStaus >> 1) & 0x01)
#             mod_info_all['b_running'] = ((fwStaus >> 4) & 0x01)
#             mod_info_all['b_commited'] = ((fwStaus >> 5) & 0x01)
#             mod_info_all['a_mcu_ver'] = "{}.{}.{}".format( rlp[2], rlp[3], ((rlp[4] << 8) | rlp[5]) )

#             sub_mcu_imageA_ver = struct.unpack('>I', rlp[6:10])[0]  #142-145
#             mod_info_all['a_sub_mcu_ver'] = "{}".format( a.dot_split_style_version1(sub_mcu_imageA_ver) )

#             # tmp_txt = ('<tr><td>Sub MCU Running Img </td><td> %d</td></tr>' % rlp[10])  #146
#             # ret_txt += tmp_txt
#             dsp_imageA_ver = struct.unpack('>I', rlp[11:15])[0]  #147-150
#             mod_info_all['a_dsp_ver'] = "{}".format( a.dot_split_style_version(dsp_imageA_ver) )
            
#             mod_info_all['b_mcu_ver'] = "{}.{}.{}".format( rlp[174 - 136], rlp[175 - 136], ((rlp[176 - 136] << 8) | rlp[177 - 136]) )

#             sub_mcu_imageB_ver = struct.unpack(
#                 '>I', rlp[(178 - 136):(182 - 136)])[0]  #178-181
#             mod_info_all['b_sub_mcu_ver'] = "{}".format( a.dot_split_style_version1(sub_mcu_imageB_ver) )

#             dsp_imageB_ver = struct.unpack(
#                 '>I', rlp[(182 - 136):(186 - 136)])[0]  #182-185
#             mod_info_all['b_dsp_ver'] = "{}".format( a.dot_split_style_version(dsp_imageB_ver) )
            
#             b.cdb_psw()
#             print(cmis.cfg_ver)
#             cmis_config_ver = str(cmis.cfg_ver["Major"]) + "." + str(cmis.cfg_ver["Minor"])
#             mod_info_all['module_config_table_ver'] = "{}".format( cmis_config_ver )
            
#             #-------------------------------------------------------------------------------
#             a.set_twi(1, 127, 0x00)
#             # 129-144 16 Vendor name Vendor name (ASCII)
#             vn = ''
#             for i in range(129, 145):
#                 ret = a.get_twi(1, i).split(',')[0]  #hex
#                 vn = vn + chr( int('0x' + str(ret), 16) )
#             mod_info_all['vendor_name'] = "{}".format( vn )

#             # 148-163 16 Vendor PN Part number provided by vendor (ASCII)
#             vpn = ''
#             for i in range(148, 164):
#                 ret = a.get_twi(1, i).split(',')[0]  #hex
#                 vpn = vpn + chr( int('0x' + str(ret), 16) )
#             mod_info_all['vendor_pn'] = "{}".format( vpn )

#             # 166-181 16 Vendor SN Vendor Serial Number (ASCII)
#             vsn = ''
#             for i in range(166, 182):
#                 ret = a.get_twi(1, i).split(',')[0]  #hex
#                 vsn = vsn + chr( int('0x' + str(ret), 16) )

#             mod_info_all['vendor_sn'] = "{}".format( vsn )
#         else:
#             print('Rlp check code Err...')

#         # get hw info-------------------------------------------------------------
#         b.cdb_psw()
#         flash = Flash(b)
#         startAddr = 0x308000
#         sectorNo = int(startAddr / 4096)

#         readRes = b''
#         data_len = a.read_item_from_config_ini('dev','module_config_file_len')
#         if data_len == '---':
#             pass
#         else:
#             remaining = int(data_len)
#             readout = 0
#             BLOCK_SIZE = 128
#             while remaining:
#                 if remaining >= BLOCK_SIZE:
#                     res = flash.read(startAddr+readout, BLOCK_SIZE)
#                     readRes += struct.pack('%sB'%len(res), *res)
#                     readout += BLOCK_SIZE
#                     remaining -= BLOCK_SIZE
#                 else:
#                     res = flash.read(startAddr+readout, remaining)
#                     readRes += struct.pack('%sB'%len(res), *res)
#                     readout += remaining
#                     remaining -= remaining
#             # print(readRes)

#             flash_data = ''.join(['%04X ' %x  for x in readRes])
#             # print("DATA: {}".format(flash_data))
#             fdl = flash_data.split(" ")

#             mod_info_all['pcbm_ver'] = "{}".format( str(int('0x' + fdl[19] + fdl[18]+ fdl[17]+ fdl[16], 16)) )
#             mod_info_all['pcbs_ver'] = "{}".format( str(int('0x' + fdl[23] + fdl[22]+ fdl[21]+ fdl[20], 16)) )
#             mod_info_all['dsp_ver'] = "{}".format( str(int('0x' + fdl[27] + fdl[26]+ fdl[25]+ fdl[24], 16)) )
#             mod_info_all['cosa_ver'] = "{}".format( str(int('0x' + fdl[31] + fdl[30]+ fdl[29]+ fdl[28], 16)) )
#             mod_info_all['itla_ver'] = "{}".format( str(int('0x' + fdl[35] + fdl[34]+ fdl[33]+ fdl[32], 16)) )

#         # return json.dumps(mod_info_all)
#         for k,v in mod_info_all.items():
#             row = [k, v]
#             print(row)
#             sheet_modinfo.append(row) 


#     # DDM-------------------------------------------------------------
#     if ckb_DDM == 'DDM':
#         print('Export DDM ....')
#         sheet_ddm = wb.create_sheet('DDM',index=0)
#         sheet_ddm.append(['Name', 'Value'])

#         b = Broker()
#         b.twi_sbw(122, b'\xa5\x5a\x5a\xa5')
#         # COSA Temperatureï¼?COSA_TEMP_OUT
#         # PCBA Temperature ï¼šPCB_TEMP_ADC
#         ain = Ain(b, 'COSA_TEMP_OUT')
#         cosa_temp = ain.aval
#         ain = Ain(b, 'PCB_TEMP_ADC')
#         pcba_temp = ain.aval
#         d = DDM(b)
#         ddt = d.dsp_die_temp

#         sheet_ddm.append(['TX Power (dbm)',  str( round(d.tx_power, 2) )])
#         sheet_ddm.append(['RX Power (dbm)',  str( round(d.rx_power, 2) )])
#         sheet_ddm.append(['Vcc (V)',  str(round(d.vcc, 2))])
#         sheet_ddm.append(['COSA Temperature (ºC)', str(round(cosa_temp, 2))  ])
#         sheet_ddm.append(['PCBA Temperature (ºC) ', str(round(pcba_temp, 2)) ])
#         sheet_ddm.append(['Case Temperature (ºC)', str(round(d.case_temp, 2)) ])
#         sheet_ddm.append(['Laser Temperature (ºC)', str(round(d.laser_temp, 2)) ])
#         sheet_ddm.append(['DSP Temperature (ºC) ', str(round(d.dsp_temp, 2)) ])
#         sheet_ddm.append(['DSP Die Temperature hrx2(ºC)',  str(round(ddt[0], 2))])
#         sheet_ddm.append(['DSP Die Temperature lrx(ºC)', str(round(ddt[1], 2)) ])
#         sheet_ddm.append(['DSP Die Temperature ltx_v(ºC)', str(round(ddt[2], 2)) ])
#         sheet_ddm.append(['DSP Die Temperature htx_top0(ºC)', str(round(ddt[3], 2)) ])


#     # PAGES_DATA-------------------------------------------------------------
#     if ckb_PAGES_DATA == 'PAGES_DATA':
#         print('Export PAGES_DATA ....')
#         # sheet_pages_data = wb.create_sheet('PAGES_DATA',index=0)
#         page_file = './templates/files/OSFP_GUI_CMIS_MMR.xlsm'

#         # print('----------------------------------------------------------------------')
#         xl = pd.ExcelFile(page_file)

#         sheet_names = xl.sheet_names

#         print(sheet_names)
#         print(type(sheet_names))

#         sheet_names.reverse()
#         for sheet_name in sheet_names:
#             if 'Sheet' in sheet_name:
#                 continue

#             print(sheet_name)
#             sheet_pages_data = wb.create_sheet(sheet_name, index=0)
#             sheet_pages_data.append(['Address','Name', 'Dec', 'Hex', 'Bin', 'Chr' ])

#             data = pd.read_excel('./templates/files/OSFP_GUI_CMIS_MMR.xlsm',
#                      sheet_name=sheet_name,
#                      usecols=[0, 1, 2, 3, 4, 5],
#                      skiprows=[0])

#             if sheet_name == "Lower Page":
#                 pass
#             else: # Upper page
#                 print("Switch page ...")
#                 page_select_byte = '0x' + sheet_name.split(' ')[1][0:2]
#                 # a.set_twi(1, 126, bank)     
#                 a.set_twi(1, 127, page_select_byte)    

#             for index, row in data.iterrows():
#                 row_list = []
#                 ret = a.get_twi(1, row[0])
#                 ret1 = ret.split(',')[0]  #hex
                 
#                 row_list.append(row[0])
#                 row_list.append(row[1])
#                 row_list.append(int(ret1, 16))
#                 row_list.append(ret1.upper())
#                 row_list.append('{:08b}'.format(int(ret1, 16)))

#                 if int(ret1, 16) > 32 and int(ret1, 16) < 127:
#                     row_list.append(chr(int(ret1, 16)))
#                 else:
#                     row_list.append('')

#                 sheet_pages_data.append(row_list)


#     d = datetime.now().timetuple()   
#     dt = "{}{:02}{:02}_{:02}{:02}{:02}".format(d[0],d[1],d[2],d[3],d[4],d[5])

#     a.set_twi(1, 127, 0x00)
#     vsn = ''
#     for i in range(166, 182):
#         ret = a.get_twi(1, i).split(',')[0]  #hex
#         vsn = vsn + chr( int('0x' + str(ret), 16) )

#     print(vsn)
#     filename = "SN_" + vsn.strip() + "_" + dt + ".xlsx"
#     wb.save('./static/files/' + filename)  
#     return filename
#     # return send_file('./static/files/' + parameters_file, attachment_filename="parameters.xlsx", as_attachment=True)




# # ALARMS AND FAULTS
# @module_bp.route('/af')
# def af():
#     # read excel template and fill a data structure
#     af_file = './templates/files/QDD_alarm_fault_Reg.xlsx'
#     # page_name = 'Lower Page'
#     # page_name = 'Page 11H'
#     page_name = request.args['page_name']

#     # print('----------------------------------------------------------------------')
#     xl = pd.ExcelFile(af_file)
#     # return xl.sheet_names
#     # print(xl.sheet_names)

#     sheets_page_description_list = []
#     sheet_names = xl.sheet_names
#     for sheet_name in sheet_names:
#         sheet_data = pd.read_excel(af_file, sheet_name=sheet_name, usecols=[0], skiprows=None)
#         page_description = list(sheet_data.columns.values)[0]
    
#         # print(page_description)
#         page_description_list = [sheet_name, page_description]
#         sheets_page_description_list.append(page_description_list)

#     # print(sheets_page_description_list)
#     # print('----------------------------------------------------------------------')

#     data = pd.read_excel(af_file,
#                          sheet_name=page_name,
#                          usecols=[0, 1, 2, 3, 6],
#                          skiprows=[0])

#     data = data.fillna(value='')
#     big_list = []
#     group_list = []
#     for index, row in data.iterrows():
#         row_list = []
#         row_list.append(page_name)
#         for i in range(len(row)):
#             print(row[i])
#             row_list.append(row[i])

#         big_list.append(row_list)

#     # print("-----"*20)
#     # print(big_list)
#     # print("-----"*20)
#     for i in range(0, len(big_list), 8):
#         group_list.append( [big_list[i][0],big_list[i][1],big_list[i][2], big_list[i:i+8]] )


#     page_description = '-'
#     for item in sheets_page_description_list:
#         if page_name in item:
#             page_description = item[1].replace('\n', '')

#     # print("====="*20)
#     # print(group_list)
#     # print("====="*20)
#     return render_template('alarms.html', title='Alarms/Faults', 
#         group_list = group_list, 
#         sheets_page_description_list = sheets_page_description_list,
#         page_description = page_description,
#         for_customer=for_customer)



# @module_bp.route('/api/af_get', methods=['POST'])
# def af_get():
#     bank = int(request.form["bank"])
#     page = request.form["page"]
#     byte = int(request.form["byte"])

#     print('af_get ...')
#     print(bank)
#     print(page)
#     print(byte)

#     pb_list = []
#     if page == "Lower Page":
#         pass
#     else: # Upper page
#         print("Switch page ...")
#         page_select_byte = '0x' + page.split(' ')[1][0:2]
#         a.set_twi(1, 126, bank)     
#         a.set_twi(1, 127, page_select_byte)     

#     ret = a.get_twi(1, int(byte))
#     ret1 = ret.split(',')[0]  #hex
#     bits_vals = '{:08b}'.format(int(ret1, 16))
#     print(bits_vals)

#     for bit in [0,1,2,3,4,5,6,7]:
#         if bits_vals[::-1][bit] == '0':
#             color = 'green'
#         else:
#             color = 'red'

#         pbb_list = [bank, page, byte, bit, color]
#         pb_list.append(pbb_list)

#     print(pb_list)
#     return json.dumps(pb_list)


# ##########################################################################
# def cmis_data_saveto_html(ts, cmis_data, module_state):
#     print('save to html')
#     head = """
# <!DOCTYPE html>
# <html lang="en">
# <head>
#     <meta charset="UTF-8">
#     <meta name="viewport" content="width=device-width, initial-scale=1.0">
#     <meta http-equiv="X-UA-Compatible" content="ie=edge">
#     <title>cmis data</title>
# </head>
# <body>

# </body>
# </html>
# """
#     foot = """
# </body>
# </html>
#     """
#     cmis_data_path = './static/files/cmis_data_' + ts + '.html'
#     with open(cmis_data_path, 'w') as f:
#         f.write(head)
#         f.write("<b>CMIS EEPROM in " + module_state + " mode</b><br>")
#         for key,values in cmis_data.items():
#             f.write("<b>" + key + '</b><br>')
#             for v in values:
#                 f.write(v + ' ')
#             f.write('<br>')
#         f.write(foot)
#     return cmis_data_path


# def cmis_data_saveto_txt(ts, cmis_data, module_state):
#     print('save to txt')
#     cmis_data_path = './static/files/cmis_data_' + ts + '.txt'
#     with open(cmis_data_path, 'w') as f:
#         f.write("CMIS EEPROM in " + module_state + " mode \n")
#         for key,values in cmis_data.items():
#             f.write(key + '\n')
#             for v in values:
#                 f.write(v + ' ')
#             f.write('\n')
#     return cmis_data_path


# def cmis_data_saveto_csv(ts, cmis_data, module_state):
#     print('save to csv')
#     cmis_data_path = './static/files/cmis_data_' + ts + '.csv'
#     with open(cmis_data_path, 'w', newline='') as f:
#         # writer = csv.writer(f, dialect='excel')
#         writer = csv.writer(f)
#         data = []
#         for key,values in cmis_data.items():
#             row = []
#             row.append(key)
#             for v in values:
#                 row.append(v)

#             data.append(row)

#         print(data)
#         writer.writerow(["CMIS EEPROM in " + module_state + " mode"])
#         for item in data:
#             writer.writerow(item)
#     return cmis_data_path

# @module_bp.route('/cmis_dump')
# def cmis_dump():
#     return render_template('cmis_dump.html',
#                            title='CMIS Dump',
#                            for_customer=for_customer)

# @module_bp.route('/api/dump_cmis_data', methods=['POST'])
# def dump_cmis_data():
#     set_password()
#     cmis_data = {}
#     p_list_data = json.loads(request.form["p_list_data"])
#     print(p_list_data)

#     format_list_data = json.loads(request.form["format_list_data"])
#     print(format_list_data)
    
#     #step 1, dump lower page data
#     row = []
#     for addr in range(0, 128):
#         ret = a.get_twi(1, addr)
#         ret1 = ret.split(',')[0]
#         # print(ret1)
#         # print("addr:{}  val:{}".format(addr, ret1))
#         row.append(ret1)

#     cmis_data.update({"CMIS Lower Page": row})

#     #step 2, switch pages, dump upper page data, loop here
#     # print('----------- LOWER PAGE #00 -----------')
#     for p in p_list_data:
#         #swith page
#         # page_select_byte = int('0x' + p, 16)
#         page_select_byte = '0x' + p
#         print(page_select_byte)
#         a.set_twi(1, 127, page_select_byte)
#         # time.sleep(0.001)

#         # print('----------- UPPER PAGE #' + p + ' -----------')
#         row = []
#         for addr in range(128, 256):
#             ret = a.get_twi(1, addr)
#             ret1 = ret.split(',')[0]
#             # print("addr:{}  val:{}".format(addr, ret1))
#             row.append(ret1)

#         cmis_data.update({"CMIS Upper Page " + p + "h": row})

#         # print('----------------------------------------------')

#     print(cmis_data)

#     #setp 3, save and zipped data (html, csv, txt)
#     html_str = ''
#     fname_list = []
#     d = datetime.now().timetuple()   
#     ts = "{}{:02}{:02}_{:02}{:02}{:02}".format(d[0],d[1],d[2],d[3],d[4],d[5]) #'20230130_142926'

#     module_state = get_module_state()
#     print(module_state)

#     #html
#     if format_list_data[0] == 1:
#         fname_list.append(cmis_data_saveto_html(ts, cmis_data, module_state))

#     if format_list_data[1] == 1:
#         fname_list.append(cmis_data_saveto_txt(ts, cmis_data, module_state))

#     if format_list_data[2] == 1:
#         fname_list.append(cmis_data_saveto_csv(ts, cmis_data, module_state))
    
#     #setp 4, return download link entry
#     print(fname_list)

#     if len(fname_list) > 0:
#         #zipped files
#         f = zipfile.ZipFile('./static/files/cmis_data_'+ ts +'.zip','w',zipfile.ZIP_DEFLATED)
#         for i in fname_list:
#             file = i.split('/')[-1]
#             f.write(i, file)
#         f.close()

#         html_str = "Download: <a href=./static/files/cmis_data_" + ts + ".zip" + ">cmis_data_" + ts +'.zip' + "</a> &nbsp;&nbsp;&nbsp;&nbsp;"

#     return html_str



##################################################
# DASHBOARD,  demo only
##################################################

@module_bp.route('/')
@module_bp.route('/dashboard')
def dashboard():
    return render_template('dashboard.html', title='Dashboard', for_customer=for_customer)


##################################################
# CONSOLE PAGE
##################################################
@module_bp.route('/console1')
def console1():
    return render_template('console.html', title='Console',for_customer=for_customer)


@module_bp.route('/api/handle_console1', methods=['POST'])
def handle_console1():
    cmd_str = request.form["cmd_str"]
    ret = a.connect_query(cmd_str)
    return ret


@module_bp.route('/api/get_product')
def get_product():
    # PRODUCT =  a.read_item_from_config_ini('dev', 'product')
    PRODUCT = a.get_product()
    IP_ADDR = a.read_item_from_config_ini('dev', 'ip')
    return PRODUCT + "," + IP_ADDR


@module_bp.route('/api/btn_reconnect', methods=['POST'])
def btn_reconnect():
    os.system("Reload.bat")
    return "btn_reconnect... ok"


ports = [
    ['Port1', '4', '0x70', '0x1', '0x50'],
    ['Port2', '4', '0x70', '0x2', '0x50'],
    ['Port3', '4', '0x70', '0x4', '0x50'],
    ['Port4', '4', '0x70', '0x8', '0x50'],
    ['Port5', '4', '0x70', '0x10', '0x50'],
    ['Port6', '4', '0x70', '0x20', '0x50'],
    ['Port7', '4', '0x70', '0x40', '0x50'],
    ['Port8', '4', '0x70', '0x80', '0x50'],
    ['Port9',  '5', '0x70', '0x1', '0x50'],
    ['Port10', '5', '0x70', '0x2', '0x50'],

    ['Port11', '5', '0x70', '0x4', '0x50'],
    ['Port12', '5', '0x70', '0x8', '0x50'],
    ['Port13', '5', '0x70', '0x10', '0x50'],
    ['Port14', '5', '0x70', '0x20', '0x50'],
    ['Port15', '5', '0x70', '0x40', '0x50'],
    ['Port16', '5', '0x70', '0x80', '0x50'],
    ['Port17', '6', '0x70', '0x1', '0x50'],
    ['Port18', '6', '0x70', '0x2', '0x50'],
    ['Port19', '6', '0x70', '0x4', '0x50'],
    ['Port20', '6', '0x70', '0x8', '0x50'],

    ['Port21', '6', '0x70', '0x10', '0x50'],
    ['Port22', '6', '0x70', '0x20', '0x50'],
    ['Port23', '6', '0x70', '0x40', '0x50'],
    ['Port24', '6', '0x70', '0x80', '0x50'],
    ['Port25', '7', '0x70', '0x1', '0x50'],
    ['Port26', '7', '0x70', '0x2', '0x50'],
    ['Port27', '7', '0x70', '0x4', '0x50'],
    ['Port28', '7', '0x70', '0x8', '0x50'],
    ['Port29', '7', '0x70', '0x10', '0x50'],
    ['Port30', '7', '0x70', '0x20', '0x50'],
    
    ['Port31', '7', '0x70', '0x40', '0x50'],
    ['Port32', '7', '0x70', '0x80', '0x50'],
]


@module_bp.route('/i2c_port_rw')
def i2c_port_rw():
    return render_template('i2c_port_rw.html',
                           title='I2C Port Read/Write',
                           ports=ports)


@module_bp.route('/api/btn_i2c_port_get', methods=['POST'])
def btn_i2c_port_get():
    print("btn_i2c_port_get ...")

    port = str(request.form["port"])
    reg = str(request.form["reg"])

    for p in ports:
        if port in p:
            bus = p[1]
            mux_id = p[2]
            chan = p[3]
            eeprom_id = p[4]
            # i2cset -y 4 0x70 0x1
            # i2cget -y 4 0x50 0x0

            sel_cmd = "i2cset -y {} {} {}".format(bus, mux_id, chan)
            get_cmd = "i2cget -y {} {} {}".format(bus, eeprom_id, reg)

            print(sel_cmd)
            print(get_cmd)
            # call broker instance api

    return "0x10"



@module_bp.route('/api/btn_i2c_port_set', methods=['POST'])
def btn_i2c_port_set():
    print("btn_i2c_port_set ...")

    port = request.form["port"]
    reg = request.form["reg"]
    val = request.form["val"]

    for p in ports:
        if port in p:
            bus = p[1]
            mux_id = p[2]
            chan = p[3]
            eeprom_id = p[4]
            # i2cset -y 4 0x70 0x1
            # i2cget -y 4 0x50 0x0
            # i2cset -y 4 0x50 0x0 0x12

            sel_cmd = "i2cset -y {} {} {}".format(bus, mux_id, chan)
            # get_cmd = "i2cget -y 4 0x50 0x0".format(bus, eeprom_id, reg)
            set_cmd = "i2cset -y {} {} {} {}".format(bus, eeprom_id, reg, val)

            print(sel_cmd)
            print(set_cmd)
            # call broker instance api

    return "btn_i2c_port_set ok"




@module_bp.route('/module_reset')
def module_reset():
    return render_template('module_reset.html',
                           title='Module Reset',
                           port_g1=[1,2,3,4,5,6,7,8],
                           port_g2=[9,10,11,12,13,14,15,16],
                           port_g3=[17,18,19,20,21,22,23,24],
                           port_g4=[25,26,27,28,29,30,31,32])



@module_bp.route('/api/mod_reset_set', methods=['POST'])
def mod_reset_set():
    Port1 = request.form["Port1"]
    Port2 = request.form["Port2"]
    Port3 = request.form["Port3"]
    Port4 = request.form["Port4"]
    Port5 = request.form["Port5"]
    Port6 = request.form["Port6"]
    Port7 = request.form["Port7"]
    Port8 = request.form["Port8"]
    Port9 = request.form["Port9"]
    Port10 = request.form["Port10"]
    Port11 = request.form["Port11"]
    Port12 = request.form["Port12"]
    Port13 = request.form["Port13"]
    Port14 = request.form["Port14"]
    Port15 = request.form["Port15"]
    Port16 = request.form["Port16"]
    Port17 = request.form["Port17"]
    Port18 = request.form["Port18"]
    Port19 = request.form["Port19"]
    Port20 = request.form["Port20"]
    Port21 = request.form["Port21"]
    Port22 = request.form["Port22"]
    Port23 = request.form["Port23"]
    Port24 = request.form["Port24"]
    Port25 = request.form["Port25"]
    Port26 = request.form["Port26"]
    Port27 = request.form["Port27"]
    Port28 = request.form["Port28"]
    Port29 = request.form["Port29"]
    Port30 = request.form["Port30"]
    Port31 = request.form["Port31"]
    Port32 = request.form["Port32"]

    mod_reset_status = {
        "Port1":Port1,
        "Port2":Port2,
        "Port3":Port3,
        "Port4":Port4,
        "Port5":Port5,
        "Port6":Port6,
        "Port7":Port7,
        "Port8":Port8,
        "Port9":Port9,
        "Port10":Port10,
        "Port11":Port11,
        "Port12":Port12,
        "Port13":Port13,
        "Port14":Port14,
        "Port15":Port15,
        "Port16":Port16,
        "Port17":Port17,
        "Port18":Port18,
        "Port19":Port19,
        "Port20":Port20,
        "Port21":Port21,
        "Port22":Port22,
        "Port23":Port23,
        "Port24":Port24,
        "Port25":Port25,
        "Port26":Port26,
        "Port27":Port27,
        "Port28":Port28,
        "Port29":Port29,
        "Port30":Port30,
        "Port31":Port31,
        "Port32":Port32,
    }
    print("Module reset ...")
    print(mod_reset_status)
    # Call handle api----------------------------------------
    # OSFP Reset - deassert
    # i2cset -y 1 0x41 0x30 0x00
    # i2cset -y 1 0x41 0x31 0x00
    # i2cset -y 1 0x45 0x30 0x00
    # i2cset -y 1 0x45 0x31 0x00
    return "mod_reset_set... ok"


@module_bp.route('/api/btn_mod_reset_get')
def btn_mod_reset_get():
    mod_reset_status = {}
    for i in range(32):
        mod_reset_status.update({"Port"+str(i+1): 1})

    return json.dumps(mod_reset_status) 



@module_bp.route('/module_lpmode')
def module_lpmode():
    return render_template('module_lpmode.html',
                           title='Module LPMode',
                           port_g1=[1,2,3,4,5,6,7,8],
                           port_g2=[9,10,11,12,13,14,15,16],
                           port_g3=[17,18,19,20,21,22,23,24],
                           port_g4=[25,26,27,28,29,30,31,32])


@module_bp.route('/api/mod_lpmode_set', methods=['POST'])
def mod_lpmode_set():
    Port1 = request.form["Port1"]
    Port2 = request.form["Port2"]
    Port3 = request.form["Port3"]
    Port4 = request.form["Port4"]
    Port5 = request.form["Port5"]
    Port6 = request.form["Port6"]
    Port7 = request.form["Port7"]
    Port8 = request.form["Port8"]
    Port9 = request.form["Port9"]
    Port10 = request.form["Port10"]
    Port11 = request.form["Port11"]
    Port12 = request.form["Port12"]
    Port13 = request.form["Port13"]
    Port14 = request.form["Port14"]
    Port15 = request.form["Port15"]
    Port16 = request.form["Port16"]
    Port17 = request.form["Port17"]
    Port18 = request.form["Port18"]
    Port19 = request.form["Port19"]
    Port20 = request.form["Port20"]
    Port21 = request.form["Port21"]
    Port22 = request.form["Port22"]
    Port23 = request.form["Port23"]
    Port24 = request.form["Port24"]
    Port25 = request.form["Port25"]
    Port26 = request.form["Port26"]
    Port27 = request.form["Port27"]
    Port28 = request.form["Port28"]
    Port29 = request.form["Port29"]
    Port30 = request.form["Port30"]
    Port31 = request.form["Port31"]
    Port32 = request.form["Port32"]

    mod_lpmode_status = {
        "Port1":Port1,
        "Port2":Port2,
        "Port3":Port3,
        "Port4":Port4,
        "Port5":Port5,
        "Port6":Port6,
        "Port7":Port7,
        "Port8":Port8,
        "Port9":Port9,
        "Port10":Port10,
        "Port11":Port11,
        "Port12":Port12,
        "Port13":Port13,
        "Port14":Port14,
        "Port15":Port15,
        "Port16":Port16,
        "Port17":Port17,
        "Port18":Port18,
        "Port19":Port19,
        "Port20":Port20,
        "Port21":Port21,
        "Port22":Port22,
        "Port23":Port23,
        "Port24":Port24,
        "Port25":Port25,
        "Port26":Port26,
        "Port27":Port27,
        "Port28":Port28,
        "Port29":Port29,
        "Port30":Port30,
        "Port31":Port31,
        "Port32":Port32,
    }
    print("Module LPMode ...")
    print(mod_lpmode_status)
    # Call handle api----------------------------------------
    # OSFP LPMode - High
    # i2cset -y 1 0x41 0x34 0x00
    # i2cset -y 1 0x41 0x35 0x00
    # i2cset -y 1 0x45 0x34 0x00
    # i2cset -y 1 0x45 0x35 0x00
    return "mod_lpmode_set... ok"


@module_bp.route('/api/btn_mod_lpmode_get')
def btn_mod_lpmode_get():
    mod_lpmode_status = {}
    for i in range(32):
        mod_lpmode_status.update({"Port"+str(i+1): 1})

    return json.dumps(mod_lpmode_status) 


@module_bp.route('/port_err_alm_checker')
def port_err_alm_checker():
    return render_template('port_err_alm_checker.html',
                           title='Port Error/Alarm Checker',
                           port_g1=[1,2,3,4,5,6,7,8],
                           port_g2=[9,10,11,12,13,14,15,16],
                           port_g3=[17,18,19,20,21,22,23,24],
                           port_g4=[25,26,27,28,29,30,31,32])


@module_bp.route('/api/btn_port_err_alm_checker_get')
def btn_port_err_alm_checker_get():
    port_err_alm_checker_status = {}
    for i in range(32):
        port_err_alm_checker_status.update({"Port"+str(i+1): random.randint(0,1)})

    # Call handle api----------------------------------------
    # i2cget -y 1 0x41 0x40 (port 1-8)
    # i2cget -y 1 0x41 0x41 (port 9-16)
    # i2cget -y 1 0x45 0x40 (port 17-24)
    # i2cget -y 1 0x45 0x41 (port 25-32)
    # 0: Module Interrupt
    # 1: Normal Operation
    return json.dumps(port_err_alm_checker_status) 
